我目前使用硒webdriver解析通过facebook用户的朋友页面,并从AJAX脚本提取所有id。但我需要向下滚动来找到所有的朋友。如何向下滚动硒。我正在使用python。


当前回答

你可以使用send_keys来模拟PAGE_DOWN键(通常滚动页面):

from selenium.webdriver.common.keys import Keys
html = driver.find_element_by_tag_name('html')
html.send_keys(Keys.PAGE_DOWN)

其他回答

如果你想滚动到无限页面的底部(如linkedin.com),你可以使用下面的代码:

SCROLL_PAUSE_TIME = 0.5

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

参考:https://stackoverflow.com/a/28928684/1316860

element=find_element_by_xpath("xpath of the li you are trying to access")

element.location_once_scrolled_into_view

当我试图进入一个不可见的“li”时,这很有帮助。

出于我的目的,我想要更多地向下滚动,记住窗口的位置。我的解决方案类似,使用window.scrollY

driver.execute_script("window.scrollTo(0, window.scrollY + 200)")

哪个会到当前的y轴滚动位置+ 200

当使用youtube时,浮动元素给出值“0”作为滚动高度 与其使用return document。body。scrollHeight"尝试使用这个"return document。documentelement。scrollHeight" 根据您的网速调整滚动暂停时间 否则它将只运行一次,然后在此之后中断。

SCROLL_PAUSE_TIME = 1

# Get scroll height
"""last_height = driver.execute_script("return document.body.scrollHeight")

this dowsnt work due to floating web elements on youtube
"""

last_height = driver.execute_script("return document.documentElement.scrollHeight")
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0,document.documentElement.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.documentElement.scrollHeight")
    if new_height == last_height:
       print("break")
       break
    last_height = new_height

医生说 类ActionChains完成工作:

from selenium import webdriver
from selenium.webdriver import ActionChains

driver = webdriver.Firefox()
action_chains = ActionChains(driver)
action_chains.scroll(x: int, y: int, delta_x: int, delta_y: int, duration: int = 0, origin: str = 'viewport').perform()