Python Selenium-使用元素时出现过时元素引用异常。单击()
错误输出:Python Selenium-使用元素时出现过时元素引用异常。单击(),python,python-3.x,selenium,web-scraping,css-selectors,Python,Python 3.x,Selenium,Web Scraping,Css Selectors,错误输出: 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
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
由于您使用的是driver.back(),因此它刷新了页面,并且您捕获的元素不再附加到页面上。您需要重新分配这些元素 试试下面的代码
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)
由于您使用的是driver.back(),因此它刷新了页面,并且您捕获的元素不再附加到页面上。您需要重新分配这些元素 试试下面的代码
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)
啊,这解决了我的问题啊,这解决了我的问题