我正在尝试自动执行Instagram Direct上的滚动操作,以便能够开始Instagram聊天。另外,我认为无法使用xpath选择滚动条,因此可能有必要使用带有“ home”键或“ page up”的自动按键循环。但是说实话,我真的不知道该怎么做。附言:如果按住“ home”键,您只能在滚动停止之前向上滚动几页,因此您需要在几秒钟后释放该键以继续向上滚动。因此,也许这不是执行我要寻找的最佳方法。希望有人能帮助我,非常感谢!
源代码:
from selenium import webdriver
from time import sleep
from secrets import username, pw
from selenium.webdriver.chrome.options import Options
mobile_emulation = {
"deviceMetrics": { "width": 360, "height": 640, "pixelRatio": 3.0 },
"userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19" }
chrome_options = Options()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
class MsgBot:
def __init__(self):
self.driver = webdriver.Chrome(chrome_options = chrome_options)
self.driver.get("https://instagram.com")
sleep(2)
self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div/div/div/div[2]/button').click()
sleep(5)
login_input = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div/div/div/form/div[4]/div/label/input')
login_input.send_keys(username)
pw_input = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div/div/div/form/div[5]/div/label/input')
pw_input.send_keys(pw)
login_btn = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div/div/div/form/div[7]/button').click()
sleep(4)
self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/button').click()
sleep(4)
self.driver.find_element_by_xpath('/html/body/div[4]/div/div/div[3]/button[2]').click()
sleep(2)
self.driver.find_element_by_xpath('//*[@id="react-root"]/section/nav[1]/div/div/header/div/div[2]/a/div').click()
sleep(4)
self.driver.find_element_by_xpath('/html/body/div[4]/div/div/div[3]/button[2]').click()
sleep(4)
self.driver.find_element_by_xpath('//*[@id="react-root"]/section/div[2]/div/div/div[2]/div/div[2]/a').click()
sleep(3)
#scroll should begin
MsgBot()
要滚动到该元素,可以使用:
from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
element = driver.find_element_by_id("id")
actions.move_to_element(element).perform()
或
driver.execute_script("arguments[0].scrollIntoView();", element)
使用JavaScript代码滚动到元素