如何在python中使用selenium webdriver滚动网页?

use*_*364 100 python selenium automated-tests selenium-webdriver

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

OWA*_*DVL 194

您可以使用

driver.execute_script("window.scrollTo(0, Y)") 
Run Code Online (Sandbox Code Playgroud)

其中Y是高度(在全高清监视器上它是1080).(感谢@lukeis)

你也可以使用

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
Run Code Online (Sandbox Code Playgroud)

滚动到页面底部.

如果你想scrool到一个无限加载的页面,如社交网络,Facebook等(感谢@Cong 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
Run Code Online (Sandbox Code Playgroud)

  • 完美的答案! (3认同)
  • 太好了,你能解释一下 `scrollHeight` 是什么意思,它一般是如何工作的吗? (2认同)

Cuo*_*ran 61

如果要向下滚动到无限页面的底部(如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
Run Code Online (Sandbox Code Playgroud)

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

  • `SCROLL_PAUSE_TIME` 变化,我需要大约 2 秒。 (3认同)
  • 这很棒。对于任何试图在 Instagram 上使用此功能的人,您可能需要首先使用 ActionChains 选择“加载更多”按钮,然后应用 Cuong Tran 的解决方案……至少这对我有用。 (2认同)

luk*_*eis 19

此处显示的方法相同:

在python中你可以使用

driver.execute_script("window.scrollTo(0, Y)")
Run Code Online (Sandbox Code Playgroud)

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


LIU*_*YUE 18

from selenium.webdriver.common.keys import Keys
html = browser.find_element_by_tag_name('html')
html.send_keys(Keys.END)
Run Code Online (Sandbox Code Playgroud)

测试,它的工作原理

  • Selenium 不再支持 `find_element_by_tag_name`。此外,按键在 Facebook 等页面上也不起作用。 (4认同)

pre*_*ion 12

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

element.location_once_scrolled_into_view
Run Code Online (Sandbox Code Playgroud)

当我试图访问一个看不见的'li'时,这有帮助.


小智 8

下面是一个示例 selenium 代码片段,您可以将其用于此类目的。它会转到“枚举 python 教程”上的 YouTube 搜索结果的网址,然后向下滚动,直到找到标题为“枚举 python 教程(2020)”的视频。

driver.get('https://www.youtube.com/results?search_query=enumerate+python')
target = driver.find_element_by_link_text('Enumerate python tutorial(2020).')
target.location_once_scrolled_into_view
Run Code Online (Sandbox Code Playgroud)


Nic*_*ady 7

出于我的目的,我想向下滚动更多,同时牢记窗口的位置。我的解决方案是相似的,并使用window.scrollY

driver.execute_script("window.scrollTo(0, window.scrollY + 200)")
Run Code Online (Sandbox Code Playgroud)

它将转到当前的y滚动位置+ 200


小智 7

这是您向下滚动网页的方式:

driver.execute_script("window.scrollTo(0, 1000);")
Run Code Online (Sandbox Code Playgroud)


ash*_*hra 7

滚动加载页面。示例:medium、quora 等

last_height = driver.execute_script("return document.body.scrollHeight")
    while True:
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight-1000);")
        # Wait to load the page.
        driver.implicitly_wait(30) # seconds
        new_height = driver.execute_script("return document.body.scrollHeight")
    
        if new_height == last_height:
            break
        last_height = new_height
        # sleep for 30s
        driver.implicitly_wait(30) # seconds
    driver.quit()
Run Code Online (Sandbox Code Playgroud)


Alb*_*ang 7

此代码滚动到底部,但不需要您每次都等待。它会不断滚动,然后停在底部(或超时)

from selenium import webdriver
import time

driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver.get('https://example.com')

pre_scroll_height = driver.execute_script('return document.body.scrollHeight;')
run_time, max_run_time = 0, 1
while True:
    iteration_start = time.time()
    # Scroll webpage, the 100 allows for a more 'aggressive' scroll
    driver.execute_script('window.scrollTo(0, 100*document.body.scrollHeight);')

    post_scroll_height = driver.execute_script('return document.body.scrollHeight;')

    scrolled = post_scroll_height != pre_scroll_height
    timed_out = run_time >= max_run_time

    if scrolled:
        run_time = 0
        pre_scroll_height = post_scroll_height
    elif not scrolled and not timed_out:
        run_time += time.time() - iteration_start
    elif not scrolled and timed_out:
        break

# closing the driver is optional 
driver.close()
Run Code Online (Sandbox Code Playgroud)

这比每次等待 0.5-3 秒等待响应要快得多,而该响应可能需要 0.1 秒


myl*_*les 6

我正在寻找一种滚动动态网页的方法,并在到达页面末尾时自动停止,并找到了这个线程。

@Cuong Tran的帖子了一个主要修改,就是我正在寻找的答案。我认为其他人可能会发现修改有用(它对代码的工作方式有明显的影响),因此这篇文章。

修改是将捕获的最后一页高度的声明循环(使每个检查比较前一页面的高度)。

所以,下面的代码:

不断向下滚动动态网页 ( .scrollTo()),仅在一次迭代中页面高度保持不变时停止。

(还有另一个修改,其中 break 语句位于另一个可以删除的条件内(以防页面“粘住”)。

    SCROLL_PAUSE_TIME = 0.5


    while True:

        # Get scroll height
        ### This is the difference. Moving this *inside* the loop
        ### means that it checks if scrollTo is still scrolling 
        last_height = driver.execute_script("return document.body.scrollHeight")

        # 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:

            # try again (can be removed)
            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")

            # check if the page height has remained the same
            if new_height == last_height:
                # if so, you are done
                break
            # if not, move on to the next loop
            else:
                last_height = new_height
                continue
Run Code Online (Sandbox Code Playgroud)


Nou*_*ama 6

您可以使用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)
Run Code Online (Sandbox Code Playgroud)

  • 这是在我工作的特定页面上与我一起使用的唯一代码,但我必须用鼠标单击滑块才能工作我不知道为什么我应该这样做,我尝试为我的问题找到另一个解决方案 (2认同)

小智 5

这些答案对我都不起作用,至少不是向下滚动Facebook搜索结果页面有效,但经过大量测试,我发现此解决方案:

while driver.find_element_by_tag_name('div'):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    Divs=driver.find_element_by_tag_name('div').text
    if 'End of Results' in Divs:
        print 'end'
        break
    else:
        continue
Run Code Online (Sandbox Code Playgroud)


小智 5

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

label.sendKeys(Keys.PAGE_DOWN);
Run Code Online (Sandbox Code Playgroud)

希望它能起作用!


Vin*_*rma 5

与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
Run Code Online (Sandbox Code Playgroud)