我刚刚开始学习Python类,这是我第一次编程,除了一点点HTML。我正在尝试为Instagram编写脚本,并希望能够将Chrome浏览器置于移动视图中。因此,我的想法是先打开开发人员工具(CTRL + SHIFT + i),然后再移动(CTRL + SHIFT + m)。如何让Selenium使用Python代码来做到这一点?
String selectAll = Keys.chord(Keys.ALT, Keys.SHIFT,"z");
driver.findElement(By.tagName("html")).sendKeys(selectAll);
我试图修改此设置以使其正常运行,但没有成功。我需要导入一些东西才能使上面的块起作用吗?
这是我拥有的代码,在现有代码运行后,我正尝试进入移动模式。
from time import sleep
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
#mobile_emulation = { "deviceName": "iPhone 4" }
#chrome_options = webdriver.ChromeOptions()
#chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
#driver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub',
#desired_capabilities = chrome_options.to_capabilities())
class InstaBot:
def __init__(self,username,pw,):
self.driver = webdriver.Chrome()
self.username = username
self.driver.get('https://instagram.com')
sleep(2)
self.driver.find_element_by_xpath("//a[contains(text(), 'Log in')]")\
.click()
sleep(2)
self.driver.find_element_by_xpath("//input[@name=\"username\"]")\
.send_keys(username)
self.driver.find_element_by_xpath("//input[@name=\"password\"]")\
.send_keys(pw)
self.driver.find_element_by_xpath('//button[@type="submit"]')\
.click()
sleep(4)
self.driver.find_element_by_xpath("//button[contains(text(), 'Not Now')]")\
.click()
sleep(4)
my_bot = InstaBot('username', 'password')
actions = ActionChains(driver)
actions.send_keys(Keys.CTRL, Keys.SHIFT, "i")
actions.perform()```
请尝试使用ActionChains
发送密钥
actions = ActionChains(self.driver)
actions.send_keys(Keys.CTRL, Keys.SHIFT, "i")
actions.perform()
进口将是
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
键看起来有点黑。
请尝试使用此方法:
from selenium import webdriver
mobile_emulation = { "deviceName": "Nexus 5" }
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub',
desired_capabilities = chrome_options.to_capabilities())