Как прокрутить страницу вниз selenium python
Перейти к содержимому

Как прокрутить страницу вниз selenium python

  • автор:

selenium-webdriver
Скроллинг

Различные прокрутки с использованием java разными способами

Ниже дать решение можно также использовать в других поддерживаемых языках программирования с некоторыми изменениями синтаксиса

  1. Выполнение Прокрутка вниз по страницам / разделу / разделению на веб-странице, в то время как есть настраиваемая полоса прокрутки (не прокрутка браузера). Нажмите здесь. Для демонстрации и проверки полосы прокрутки имеет свой независимый элемент.

В приведенном ниже коде передайте элемент полосы прокрутки и укажите точки прокрутки.

  1. Выполнение прокрутки вверх страницы / раздела / деления на веб-странице, пока есть пользовательская полоса прокрутки (не прокрутка браузера). Нажмите здесь. Для демонстрации и проверки полосы прокрутки имеет свой независимый элемент.

В приведенном ниже коде передайте элемент полосы прокрутки и укажите точки прокрутки.

  1. Чтобы выполнить прокрутку вниз, когда несколько прокрутки браузера (Встроенный браузер), и вы хотите прокрутить вниз с помощью клавиши «Вниз» . Нажмите здесь для демонстрации

В приведенном ниже коде передайте свой элемент области прокрутки, например <div> и нажмите кнопку «вниз».

  1. Чтобы выполнить прокрутку вверх, когда несколько прокрутки браузера (Встроенный браузер), и вы хотите прокрутить вверх с помощью клавиши UP UP . Нажмите здесь для демонстрации

В нижеприведенном коде передайте свой элемент области прокрутки, например <div> и нажмите клавишу вверх.

  1. Чтобы выполнить прокрутку вниз, когда несколько прокрутки браузера (Встроенный браузер), и вы хотите прокрутить вниз с помощью клавиши «Только стрелка вниз» . Нажмите здесь для демонстрации

В приведенном ниже коде передайте свой элемент области прокрутки, например <div> и нажмите клавишу «вниз».

  1. Чтобы выполнить прокрутку вверх, когда несколько прокрутки браузера (Встроенный браузер), и вы хотите прокручивать вверх с помощью клавиши «Только стрелка вверх» . Нажмите здесь для демонстрации

В приведенном ниже коде передайте свой элемент области прокрутки, например <div> и введите требуемый ключ.

  1. Чтобы выполнить прокрутку вверх / вниз при прокрутке браузера (встроенный браузер), и вы хотите прокручивать вверх / вниз только с фиксированной точкой . Нажмите здесь для демонстрации

В приведенном ниже коде передайте свою точку прокрутки. Положительное означает, что вниз и отрицательные средства прокручиваются вверх.

  1. Чтобы выполнить прокрутку вверх / вниз при прокрутке браузера (встроенный браузер), и вы хотите прокручивать вверх / вниз, чтобы сделать элемент в видимой области или динамическом прокрутке . Нажмите здесь для демонстрации

В приведенном ниже коде передайте свой элемент.

Примечание. Пожалуйста, проверьте свой случай и используйте методы. Если какой-либо случай отсутствует, дайте мне знать.

Scroll Down a Website Using Python Selenium

Scroll Down a Website Using Python Selenium

Sometimes we may want to automate tasks in a browser, like scrolling on a website. Python has a powerful web automation tool known as Selenium.

It takes control of the web browser and allows us to perform specific actions automatically. We can write a script that automatically scrolls horizontally and vertically on a website.

Install Selenium and Chrome WebDriver

To install Selenium, we use the following command.

ChromeDriver is another executable that Selenium WebDriver uses to interact with Chrome. If we want to automate tasks on the Chrome web browser, we also need to install ChromeDriver.

  1. Click on this link. Download Chrome driver according to the version of your Chrome browser and the type of operating system.
  2. If you want to find the version of your Chrome browser, click on the three dots on the top right corner of Chrome, click on Help, and select About Google Chrome. You can see the Chrome version in the about section.
  3. Extract the zip file and run the Chrome driver.

Scroll Down a Website Using Python Selenium

Here, the x_pixels indicate the number of pixels to scroll horizontally (on the x-axis), and the y_pixels refer to the number of pixels to scroll vertically (on the y axis). In this guide, we scroll only vertically so that the x_pixels will be 0.

Scroll Down by Specified Pixels

We created the WebDriver instance in the following code and specified the path to the Chrome driver. Then we have set the URL of the target website to the driver instance using the get() method.

It will open the target website in the desired browser. We have maximized Chrome’s window for a better picture using the maximize_window() .

Selenium has the feature to execute JavaScript commands through the execute_script() method. We have automated scrolling down by 1000 pixels using the method window.scrollBy() and passed this command to the JavaScript executer.

The website will automatically scroll down vertically by 1000 pixels.

Scroll Down to the Bottom of the Website

Suppose we want to scroll down to the complete bottom of the page. The document.body.scrollHeight will give the total height of the page in pixels.

We will specify this height as the number of pixels to scroll down.

Scroll Browser to a Target Element Using Selenium in Python

  1. The URL of the webpage.
  2. The XPath of the target element.
  3. The average time it takes to load the page.

The URL of the webpage can be fetched from the search bar of any browser. If the target element is inside one of the subpages, then the subpage’s address must be given instead of the website’s home page.

XPath is a language that makes navigation easier inside web pages. Like every webpage has a URL, the elements inside the webpage have unique paths.

Fetch XPath of the Website

To fetch the XPath , go to the webpage, press F12 , or right-click and choose inspect element. A panel will appear at the bottom of the browser.

A small icon of a black cursor over a square box appears on the top left-hand side of the panel.

Clicking on the icon puts the browser on an object selection mode, where hovering the cursor over the elements of the webpage will highlight it with blue color.

Clicking on an element inside object selection mode will display the HTML of that element. Right-click over the highlight HTML inside inspect panel, go to copy, and select copy XPath .

This will copy the XPath inside the clipboard.

Imports

The program requires two import packages — webdriver sub package of Selenium library and By sub package from selenium.webdriver.common.by library.

Import Driver and Fetching Target Element

This program requires chromedriver , which can be downloaded from here.

Unzip the downloaded package and copy the path of the .exe file inside the syntax parameters below.

The URL of the webpage needs to be put inside the parameters of syntax driver.get() .

The syntax driver.find_element() searches for an element, while (By.XPATH, «your XPath») searches element for the given XPath . The XPath is put inside the double-quotes.

The contents from the XPath of the webpage get stored inside a variable el , while el.click executes a click command on the element to check its behavior.

time.sleep() puts a timeout that closes the browser when the process is finished or when no elements are found.

driver.quit releases the driver.

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

Selenium Scroll Down Webpage

Do you want the Web Browser to scroll to the end of the page while using Python Selenium?

You can do that with code, the trick is to inject Javascript code to be webpage. After you load a webpage, scroll down the page by injecting javascript.You can scroll down a specific amount or all the way to the bottom.

Related course:

Scroll down webpage

Example

Before you start make sure the Selenium Web Driver is installed and that you have the selenium module installed. The web driver must be the appropriate web driver for the browser (same version). For Firefox that’s the geckoDriver, for Chrome that’s the ChromeDriver. The version of the driver must be intended for the browser version, an outdated version most likely wont work.

The selenium scroll down code is shown below. It cals the method execute_script() with the javascript to scroll to the end of the web page.

selenium scroll down

First the required modules are loaded. You’ll need the selenium module and the time module.

Then initialize the web browser. This can be Firefox or another supported browser (Chrome, Edge, Safari)

Get your webpage wit the get() method, which has a parameter the URL to load.

Scroll Down Using Selenium in Python

To scroll down using Selenium in Python, you can use the Selenium webdriver execute_script() function which executes JavaScript code in the browser.

The Selenium Python module gives you the tools you need to be able to automate many tasks when working with web browser.

When working with web browsers, it’s possible you may want to scroll down to the bottom of a webpage or scroll down to a particular pixel height.

To scroll down using Selenium in your Python code, you can use the Selenium webdriver execute_script() function. execute_script() is a versatile function and allows you to execute JavaScript code in the browser.

With JavaScript, we can easily scroll down in a browser.

How to Scroll Down to Bottom of Webpage Using Selenium

To scroll down to the bottom of a webpage using Selenium, you can use the execute_script() function to execute the JavaScript function window.scrollTo() and pass ‘document.body.scrollHeight’ for the second parameter.

Below shows you a simple example of how you can use Selenium to scroll down to the bottom of a webpage.

How to Scroll Down to Specific Height Using Selenium

If you want to scroll down to a specific pixel height, then you can change the second parameter of the window.scrollTo() function.

For example, if you want to scroll down to pixel 600, then pass ‘600’ to window.scrollTo().

Below shows you how to use Selenium to scroll down to a specific height in your Python code.

Hopefully this article has been useful for you to learn how to scroll down using Selenium in Python.

Other Articles You'll Also Like:

  • 1. Using Python to Find Minimum Value in List
  • 2. Python Add Months to Datetime Variable Using relativedelta() Function
  • 3. PROC PHREG Equivalent in Python
  • 4. Using Python to Count Odd Numbers in List
  • 5. Get Name of Function in Python
  • 6. Python acos – Find Arccosine and Inverse Cosine of Number
  • 7. Run Something Every 5 Seconds in Python
  • 8. Check if Number is Between Two Numbers Using Python
  • 9. Using Python to Count Number of Lines in String
  • 10. Multiply Each Element in List by Scalar Value with Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *