如何在python中使用Selenium Webdriver滚动网页?

发布于 2021-02-02 23:15:51

我目前正在使用Selenium Webdriver通过Facebook用户朋友页面进行解析,并从AJAX脚本中提取所有ID。但是我需要向下滚动才能得到所有的朋友。如何在Selenium中向下滚动。我正在使用python。

关注者
0
被浏览
347
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    你可以使用

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

    其中Y是高度(在全高清显示器上为1080)。

    你也可以使用

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

    滚动到页面底部。

    如果你想滚动到无限加载的页面,例如社交网络页面,facebook等

    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
    

    另一种方法是,选择一个对象,然后

    label.sendKeys(Keys.PAGE_DOWN);
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看