如何在 python 中使用 selenium webdriver 滚动网页? [英] How can I scroll a web page using selenium webdriver in python?

查看:52
本文介绍了如何在 python 中使用 selenium webdriver 滚动网页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 selenium webdriver 解析 Facebook 用户好友页面并从 AJAX 脚本中提取所有 ID.但是我需要向下滚动才能找到所有朋友.如何在 Selenium 中向下滚动.我正在使用python.

I am currently using selenium webdriver to parse through facebook user friends page and extract all ids from the AJAX script. But I need to scroll down to get all the friends. How can I scroll down in Selenium. I am using python.

推荐答案

可以使用

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

其中 Y 是高度(在全高清显示器上是 1080).(感谢@lukeis)

where Y is the height (on a fullhd monitor it's 1080). (Thanks to @lukeis)

您也可以使用

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

滚动到页面底部.

如果您希望滚动到无限加载的页面,例如社交网络、Facebook 等(感谢@Cuong Tran)

If you want to scroll to a page with infinite loading, like social network ones, facebook etc. (thanks to @Cuong Tran)

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

另一种方法(感谢 Juanse)是,选择一个对象并

another method (thanks to Juanse) is, select an object and

label.sendKeys(Keys.PAGE_DOWN);

这篇关于如何在 python 中使用 selenium webdriver 滚动网页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆