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


当前回答

下面是我编写的一个缓慢向下滚动到targets元素的方法

你可以将CSS选择器中元素的y号位置传递给它

它就像我们通过鼠标滚轮一样滚动

一旦这个方法被调用,你用相同的驱动对象再次调用它,但是使用新的目标元素,它将在元素存在的任何地方向上/向下滚动

def slow_scroll_to_element(self, driver, element_selector=None, target_yth_location=None):
    current_scroll_position = int(driver.execute_script("return window.scrollY"))
    
    if element_selector:
        target_yth_location = int(driver.execute_script("return document.querySelector('{}').getBoundingClientRect()['top'] + window.scrollY".format(element_selector)))
    
    scrollSpeed = 100 if target_yth_location-current_scroll_position > 0 else -100

    def chunks(a, n):
        k, m = divmod(len(a), n)
        return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))
    
    for l in list(chunks(list(range(current_scroll_position, target_yth_location, scrollSpeed)) + list([target_yth_location+(-scrollSpeed if scrollSpeed > 0 else scrollSpeed)]), 3)):
        for pos in l:
            driver.execute_script("window.scrollTo(0, "+str(pos)+");")
            time.sleep(0.1)
        time.sleep(random.randint(1,3))

其他回答

方法如下图所示:

在python中,你可以使用

driver.execute_script("window.scrollTo(0, Y)")

(Y为要滚动到的垂直位置)

你可以使用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)

你可以使用send_keys来模拟一个END(或PAGE_DOWN)键按下(通常滚动页面):

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

我发现解决这个问题的最简单的方法是选择一个标签,然后发送:

label.sendKeys(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