【发布时间】:2020-08-04 11:28:59
【问题描述】:
错误输出:
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
我试图用 selenium 做以下事情:
- 去亚马逊
- 使用 python 自动搜索无聊的东西
- 点击第一个产品标题
- 如果价格标签元素在产品网站上,打印它,然后返回上一页
- 如果不可用,返回上一页
- 转到下一个产品标题并从第 4 步开始重复
但是它在click() 失败
代码:
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)
【问题讨论】:
标签: python python-3.x selenium web-scraping css-selectors