【问题标题】:Python, Selenium : 'Element is no longer attached to the DOM'Python,Selenium:'元素不再附加到 DOM'
【发布时间】:2014-07-15 04:01:55
【问题描述】:

我正在抓取一个网站,www.lipperleaders.com。我想提取新加坡的资金细节。我已经成功实现了下拉选择并提取了提交选项后出现的第一页的内容。但是当我尝试转到下一页时(通过使代码单击下一步按钮)我收到错误'Element is no longer attached to the DOM'

我的代码大约有 100 行,但我可以大致了解我的代码执行流程:

...                    # creating driver object and all the imports
def main():
    ...
    result = find_elements_by_tag_name('span')  
    ...
    driver.find_element_by_id("ctl00_ContentPlaceHolder1_ucDataPager_btnNext").click()
    main()
main()

此代码适用于第一页,但在单击下一步按钮后再次调用 main() 时。在这种递归方法之前,我也尝试将它放在一个循环中,然后也是同样的错误。

如果我编写相同的代码,例如:

# some code
result = find_elements_by_tag_name('span')  
driver.find_element_by_id("ctl00_ContentPlaceHolder1_ucDataPager_btnNext").click()
# some code
driver.find_element_by_id("ctl00_ContentPlaceHolder1_ucDataPager_btnNext").click()
.
.

此代码工作正常,没有任何错误,下一页加载并执行之后编写的代码。但是我不能为 500 页写相同的driver.find_element_by_id().click(),即使我将不得不重复与每一页相关的其余代码。这就是为什么我尝试循环或递归,但它对我不起作用。

请让我知道我的方法有什么问题。

【问题讨论】:

    标签: python selenium selenium-webdriver web-crawler


    【解决方案1】:

    这似乎是一个陈旧的元素异常,通常在您尝试查找某个元素时发生。 Which gets loaded every time but you found it earlier,所以这是陈旧的。

    我建议使用一些自定义方法来避免这种情况,最简单的解决方案之一:

    void clickOnStaleElement(String id, WebDriver driver) {
        try {
            driver.find_element_by_id(id).click();
        } catch (StaleElementReferenceException e) {
            // Trying to find element stale element
            clickOnStaleElement(id, driver);
        } catch (NoSuchElementException ele) {
            clickOnStaleElement(id, driver);
        }
     }
    

    【讨论】:

      【解决方案2】:

      问题是元素被一些 javascript 分离。所以你应该让驱动等待元素:这是通过设置implicitly_wait来完成的,见:

      from selenium import webdriver
      
      ff = webdriver.Firefox()
      ff.implicitly_wait(10) # seconds
      ...
      myDynamicElement = ff.find_element_by_id("myDynamicElement")
      

      来自 http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp#implicit-waits

      【讨论】:

      • 有效,但现在我收到新错误'Element not found in the cache - perhaps the page has changed since it was looked up'
      • 您需要在循环的每个迭代步骤中搜索元素。所以在每次迭代中你都会做类似next_button = driver.find_element_by_id('btnNextId') next_btn.click()
      • 是的,这正是我在每次迭代后点击下一步按钮移至下一页后所做的事情,但它也显示Element not found in the cache..。我清除了firefox的缓存,然后它爬了5-6页,然后又报了这个错误。
      • 嗯,这真的很奇怪......那么你可能想在没有缓存的情况下启动你的驱动程序:code.google.com/p/selenium/issues/detail?id=40
      • @InêsMartins ProfHase85 提供的链接非常有用,请参见此处:github.com/seleniumhq/selenium-google-code-issue-archive/issues/… start the driver with no cache
      猜你喜欢
      • 2014-06-06
      • 2014-10-05
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多