【问题标题】:Python Selenium not scrolling down infinite pagePython Selenium不会向下滚动无限页面
【发布时间】:2021-03-16 21:11:53
【问题描述】:

我在使用 Python Selenium 向下滚动无限滚动页面时遇到了一些问题。我想向下滚动this 页面,以便我可以点击页面上的每部电影。代码运行到最后并退出驱动程序但没有向下滚动页面 - 出了什么问题?

def scroll(driver):
    timeout = 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);")

        # load the website
        time.sleep(5)

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

driver.get("https://www.justwatch.com/uk/provider/bfi-player/movies")
scroll(driver)
driver.quit()

【问题讨论】:

  • 我正在尝试让页面向下滚动。如果需要,我可以丢失这行代码 - 我的首要任务是让页面向下滚动。

标签: python python-3.x selenium selenium-webdriver infinite-scroll


【解决方案1】:

尝试使用这个:

import time
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.justwatch.com/uk/provider/bfi-player/movies")
time.sleep(3)
driver.execute_script("document.body.getElementsByTagName('ion-content')[0].scrollToBottom();")
time.sleep(3)
driver.quit()

【讨论】:

  • 这段代码引发了这个异常:raise exception_class(message, screen, stacktrace) selenium.common.exceptions.JavascriptException: Message: javascript error: Cannot read property 'scrollToBottom' of undefined
  • @Eddyhut 怪人,我的工作很好,尝试打开浏览器-> 移动到你的 url->def 工具-> 控制台并运行该命令:document.body.getElementsByTagName('ion-content')[0].scrollToBottom();
【解决方案2】:
driver = webdriver.Chrome()


def scroll(driver):
    timeout = 5
    time.sleep(5)
    # Get scroll height
    scrollelement = driver.execute_script(
        "return document.querySelector('.tabs-inner [tab=\"popular\"] ion-content').shadowRoot.querySelector('[class=\"inner-scroll scroll-y\"]')")
    last_height = driver.execute_script(
        "return arguments[0].scrollHeight", scrollelement)
    new_height=0
    print(new_height, last_height)
    while True:
        # Scroll down to bottom
       
        driver.execute_script(
            "arguments[0].scrollTo(0, arguments[0].scrollHeight);", scrollelement)

        # load the website
        time.sleep(5)

        # Calculate new scroll height and compare with last scroll height
        new_height = driver.execute_script(
            "return arguments[0].scrollHeight", scrollelement)
        print(new_height,last_height)


driver.get("https://www.justwatch.com/uk/provider/bfi-player/movies")
scroll(driver)
driver.quit()

您应该在滚动元素上进行滚动,因为滚动条也是页面中的一个元素。但是滚动条在 shadowRoot 侧所以使用 execute_script

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-03
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-19
    • 2013-09-05
    相关资源
    最近更新 更多