Scrolling to the top of a page in Python using Selenium

I am having problems scrolling up to the top of a webpage when using Python and Selenium.

When the page loads for any reason, you are taken to the bottom of the page (this should be fixed). However, when I try to scroll to the top it doesn't work.

I tried the following:

self.driver.execute_script("scroll(0, -250);")

      

and

self.driver.execute_script("scroll(0, 0);")

      

I also tried to find the element and then loop through it:

self.driver.execute_script("arguments[0].scrollIntoView()", element)

      

The above scrollIntoView () code works when scrolling down to an element. However, scrolling doesn't work.

I've tried using Chrome Driver and PhantomJs.

Any suggestions?

+7


source to share


5 answers


You can first view item in HTML DOM

, then we can view scroll

item in like this: Viewport



element = driver.find_element_by_xpath("element_xpath")
self.driver.execute_script("return arguments[0].scrollIntoView(true);", element)

      

+4


source


You can just use CTRL + HOME keys. It will scroll to the top of the page.



driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.HOME)

      

+11


source


from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("__")

#to scroll try use the following command
driver.execute_script("scrollBy(0,250);")

      

This will work !!

0


source


Please try this:

driver.execute_script("document.querySelector('div[role=dialog] ul').parentNode.scrollTop=1e100")

      

0


source


from selenium import webdriver

if you want to scroll to the bottom of the page:

t=10
while t:
#if you want to scroll to the end of the page,use this


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

#if you want to scroll down upto some level use this, here i used "1000" you may vary 
#it according to your use


driver.execute_script("scrollBy(0,+1000);")
    sleep(3)

#if you want to scroll some level up, use this,again i used here "-1000" you may vary 
#according to your use 

driver.execute_script("scrollBy(0,+1000);")
sleep(3)
t=t-1       # it a part of the loop

      

It will definitely help you :)

0


source







All Articles