Home > Backend Development > Python Tutorial > How Can I Scroll Web Pages with Selenium WebDriver in Python?

How Can I Scroll Web Pages with Selenium WebDriver in Python?

Linda Hamilton
Release: 2024-12-19 13:02:11
Original
709 people have browsed it

How Can I Scroll Web Pages with Selenium WebDriver in Python?

How to Scroll a Web Page Using Selenium WebDriver in Python

To extract all friend IDs from the AJAX script on Facebook's user friends page, it is necessary to scroll down to gather all the information. Here's how to achieve this in Selenium using Python:

  1. Scroll to a Specific Position:
driver.execute_script("window.scrollTo(0, Y)")
Copy after login

where Y represents the desired pixel height.

  1. Scroll to the Bottom of a Page:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
Copy after login
  1. Scroll to a Page with Infinite Loading:
SCROLL_PAUSE_TIME = 0.5

last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(SCROLL_PAUSE_TIME)
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height
Copy after login
  1. Scroll Using an Object:
label.sendKeys(Keys.PAGE_DOWN);
Copy after login

By utilizing these techniques, you can effectively scroll through web pages and extract the desired data using Selenium and Python.

The above is the detailed content of How Can I Scroll Web Pages with Selenium WebDriver in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template