0

I'm trying to write a simple Python script using Selenium, and while the loop runs once, I'm getting a StaleElementReferenceException.

Here's the script I'm running:

from selenium import webdriver

browser = webdriver.Firefox()
type(browser)
browser.get('http://digital2.library.ucla.edu/Search.do?keyWord=&selectedProjects=27&pager.offset=50&viewType=1&maxPageItems=1000')
links = browser.find_elements_by_class_name('searchTitle')

for link in links:
    link.click()
    print("clicked!")
    browser.back()

I did try adding browser.refresh() to the loop, but it didn't seem to help.

I'm new to this, so please ... don't throw stuff at me, I guess.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
miriamkp
  • 13
  • 2
  • There is info at http://stackoverflow.com/a/16922300/441757 and http://stackoverflow.com/a/12982001/441757 and http://darrellgrainger.blogspot.jp/2012/06/staleelementexception.html that might be helpful – sideshowbarker Sep 14 '15 at 03:12

1 Answers1

0

It does not make sense to click through links inside of a loop. Once you click the first link, then you are no longer on the page where you got the links. Does that make sense?

Take the for loop out, and add something like link = links[0] to grab the first link, or something more specific to grab the specific link you want to click on.

If the intention is to click on every link on the page, then you can try something like the following:

links = browser.find_elements_by_class_name('searchTitle')
for i in range(len(links)):  
    links = browser.find_elements_by_class_name('searchTitle')
    link = links[i]  # specify the i'th link on the page
    link.click()
    print("clicked!")
    browser.back() 

EDIT: This might also be as simple as adding a pause after the browser.back(). You can do that with the following:

from time import sleep 
...
sleep(5) # specify pause in seconds
pocketfullofcheese
  • 8,427
  • 9
  • 41
  • 57