-1

I have a page which scrolls from the bottom (the latest feeds) to the top (the older feeds). I am trying to get Selenium to scroll all the way to the top so I can get all the information. Currently, I am using this for testing and it worked, but I have to give specific number of loops to make it work. Problem is that numbers vary so I am looking for a way where it stops when it scrolls all the way to the top.

This is working but not reusable solution.

number_of_loops = 1

while number_of_loops != 10:
    html = driver.find_element(By.TAG_NAME,'html')
    html.send_keys(Keys.PAGE_UP)
    time.sleep(1)
    print("Number of Loops:",number_of_loops)
    number_of_loops += 1

I tried this but it did not scroll at all. I think it was in a constant loop but again nothing happened.

while True:
    html = driver.find_element(By.TAG_NAME,'html')
    html.send_keys(Keys.PAGE_UP)
    time.sleep(1)

I tried some of these solutions but nothing worked so far for me.

How can I scroll a web page using selenium webdriver in python?

Scrolling to top of the page in Python using Selenium

Adriaan
  • 17,741
  • 7
  • 42
  • 75
hkay
  • 159
  • 1
  • 2
  • 12

1 Answers1

1

You can use the JS command below to scroll to the top of the page instantly.

driver.execute_script("window.scrollTo(0, 0)")
JeffC
  • 22,180
  • 5
  • 32
  • 55
  • I tried it but this didn't work either. – hkay Apr 20 '23 at 21:51
  • Post a link to the page? If it's a lazy loading page, you may need to repeatedly scroll up. – JeffC Apr 20 '23 at 22:11
  • I can't post a link due to security reasons but it seems like a lazy loading page. So there is no workaround other than repeatedly scroll up? – hkay Apr 24 '23 at 13:38
  • Correct. There is no way to scroll to the top/bottom of a lazy loading page. That's the way it's designed. – JeffC Apr 24 '23 at 13:40