0

I have following code to scroll down a javascript enabled website. Problem is when the newHeight reaches around 229275 I get list out of range on the line browser.find_elements_by_class_name('alt')[0].click(). But why I am getting this error and how can I solve this?

My code:

browser = webdriver.PhantomJS("phantomjs")
    browser.get(url)
        while True:            
         time.sleep(pause)
         newHeight = browser.execute_script("return document.body.scrollHeight")
         print newHeight
         browser.find_elements_by_class_name('alt')[0].click()
1
  • The element doesn't exist in the page at the time find_elements_by_class_name is called. It's either no longer present or not yet present. Try to wait for it or handle the case where it's no longer present. Commented Jul 20, 2017 at 22:28

3 Answers 3

1

Try to scroll down page and click element with below approach:

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException

browser = webdriver.PhantomJS("phantomjs")
browser.get(url)
while True:
    browser.find_element_by_tag_name("body").send_keys(Keys.END)
    try:
        wait(browser, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "alt"))).click()
    except NoSuchElementException:
        break

This should allow you to click required element in case it can be found or break loop otherwise

Sign up to request clarification or add additional context in comments.

Comments

0

Simply try/except statement

browser = webdriver.PhantomJS("phantomjs")
browser.get(url)
    while True:   
     try:
        time.sleep(pause)
        newHeight = browser.execute_script("return document.body.scrollHeight")
        print newHeight
        browser.find_elements_by_class_name('alt')[0].click()
     except:
        pass

Comments

0

I would recommend checking the list before acting upon it.

browser = webdriver.PhantomJS("phantomjs")
browser.get(url)
while True:            
    time.sleep(pause)
    newHeight = browser.execute_script("return document.body.scrollHeight")
    print newHeight
    alt_elements = browser.find_elements_by_class_name('alt')
    if len(alt_elements):
        alt_elements[0].click()

Just a side note, an infinite while loop can be a dangerous thing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.