I am new to Selenium and need to scrape a website that contains a list of links structured exactly like:
<a class="unique" href="...">
<i class="something"></i>
"Text - "
<span class="something">Text</span>
</a>
<a class="unique" href="...">
<i class="something"></i>
"Text - "
<span class="something">Text</span>
</a>
...
...
I need to click on this list of links inside a loop and scrape data from result pages. What I have done up till now is:
lists = browser.find_elements_by_xpath("//a[@class='unique']")
for lis in lists:
print(lis.text)
lis.click()
time.sleep(4)
# Scrape data from this page (works fine).
browser.back()
time.sleep(4)
It works fine for the first loop but when the second loop reaches
print(lis.text)
It throws an error saying:
StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
I have tried print (lists)
and it gives the list of all the link elements so works fine. The problem occurs when the browser comes back to the previous page. I have tried extending time and using browser.get(...)
instead of browser.back()
but the error still remains. I don't get why it will not print lis.text
because lists still contain a list of all the elements. Any help would be greatly appreciated.