【问题标题】:Selenium - Stale Element Reference Exception when using element.click()Selenium - 使用 element.click() 时出现过时元素引用异常
【发布时间】: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 做以下事情:

  1. 去亚马逊
  2. 使用 python 自动搜索无聊的东西
  3. 点击第一个产品标题
  4. 如果价格标签元素在产品网站上,打印它,然后返回上一页
  5. 如果不可用,返回上一页
  6. 转到下一个产品标题并从第 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


    【解决方案1】:

    由于您使用的是 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)
    

    【讨论】:

    • 啊,这解决了我的问题
    猜你喜欢
    • 2018-04-01
    • 2017-12-24
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多