Issue
Error Output:
selenium.common.exceptions.StaleElementReferenceException: Message: The element reference of <span class="a-size-medium a-color-base a-text-normal"> is stale; either
the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
I was trying to do the following with selenium:
- go to amazon
- search automate the boring stuff with python
- click the first product title
- if the price tag element, is on the product site, print it, and go back to the previous page
- if it not available, go back to the previous page
- go to the next product title and repeat from step 4
However it failed at click()
Code:
def experiment2():
browser = webdriver.Firefox()
browser.get("https://www.amazon.com/")
searchelement = browser.find_element_by_css_selector("#twotabsearchtextbox")
searchelement.send_keys('automate the boring stuff with python')
searchelement.submit()
time.sleep(5)
elements = browser.find_elements_by_css_selector("span.a-color-base.a-text-normal")
for element in elements:
element.click()
try:
element = browser.find_element_by_css_selector("span.a-size-medium:nth-child(2)")
print(element.text)
except:
browser.back()
time.sleep(2)
continue
browser.back()
time.sleep(2)
What could have caused this issue?
Solution
Since you are using driver.back() it refreshed the page and the elements you have captured it is no longer attached to the page.you need reassigned the elements again.
Try below code
def experiment2():
browser = webdriver.Firefox()
browser.get("https://www.amazon.com/")
searchelement = browser.find_element_by_css_selector("#twotabsearchtextbox")
searchelement.send_keys('automate the boring stuff with python')
searchelement.submit()
time.sleep(5)
elements = browser.find_elements_by_css_selector("span.a-color-base.a-text-normal")
for element in range(len(elements)):
elements = browser.find_elements_by_css_selector("span.a-color-base.a-text-normal")
elements[element].click()
try:
element = browser.find_element_by_css_selector("span.a-size-medium:nth-child(2)")
print(element.text)
except:
browser.back()
time.sleep(2)
continue
browser.back()
time.sleep(2)
Answered By - KunduK
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.