我刚刚开始上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
的密钥
self.driver = webdriver.Chrome(executable_path=r"C:pathtochromedriver.exe")
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
Keys看起来有点笨拙。
请尝试以下操作:
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())
参考: https://chromedriver.chromium.org/mobile-emulation