我无法修复此错误(Selenium)[过时元素引用:元素未附加到页面文档]

2024-10-02 20:35:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正试图从一个网站上获取3d打印机的价格,但我经常遇到这个错误。 代码如下:

    import selenium
    
    driver = webdriver.Chrome()
    driver.get('https://www.dx.com/p/creality-cr10-v2-upgrade-ultraquiet-twoway-sphenoid-cooling-3d-printer-eu-plug-2711457.html#.Xy6c1SgzZhE')  
    price = driver.find_elements_by_class_name('low-sale-price')
    p = price
    if not p:
        print('Printer out of stock')        
    if price != "":
        for val in price:
            a = val.text
            b = str(a)
            print(b)
            break    

这就是错误:

 Traceback (most recent call last):
 File "C:\Users\scham\Desktop\PrinterCrawler.py", line 117, in <module>
 DealExtremeEnder()
 File "C:\Users\scham\Desktop\PrinterCrawler.py", line 111, in DealExtremeEnder
 c = post.text
 File "C:\Users\scham\AppData\Local\Programs\Python\Python38-32\lib\site- 
 packages\selenium\webdriver\remote\webelement.py", line 76, in text
 return self._execute(Command.GET_ELEMENT_TEXT)['value']
 File "C:\Users\scham\AppData\Local\Programs\Python\Python38-32\lib\site- 
 packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
 return self._parent.execute(command, params)
 File "C:\Users\scham\AppData\Local\Programs\Python\Python38-32\lib\site- 
 packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
 self.error_handler.check_response(response)
 File "C:\Users\scham\AppData\Local\Programs\Python\Python38-32\lib\site- 
 packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
 raise exception_class(message, screen, stacktrace)
 selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element 
 is not attached to the page document
 (Session info: chrome=84.0.4147.105)

非常感谢您的帮助。 先谢谢你


Tags: inpyliblocalseleniumlinesiteusers
1条回答
网友
1楼 · 发布于 2024-10-02 20:35:30

我的猜测是price中的元素循环导致了StaleElementReferenceException-这意味着price列表中的元素在DOM中发生了更改,需要您再次调用driver.find_elements,以便使用非陈旧引用“刷新”元素

您可以尝试修改代码,以便在price中重新找到元素列表:

    import selenium
    
    driver = webdriver.Chrome()
    driver.get('https://www.dx.com/p/creality-cr10-v2-upgrade-ultraquiet-twoway-sphenoid-cooling-3d-printer-eu-plug-2711457.html#.Xy6c1SgzZhE')  
    price = driver.find_elements_by_class_name('low-sale-price')
    p = price
    if not p:
        print('Printer out of stock')        
    if price != "":
        for val in price:
            a = val.text
            b = str(a)
            print(b)
            
            # refresh price element list before re-iterating the loop
            price = driver.find_elements_by_class_name('low-sale-price')

            break    

相关问题 更多 >