【问题标题】:Click links one by one with Selenium webdriver Python用 Selenium webdriver Python 一一点击链接
【发布时间】:2017-03-23 09:05:05
【问题描述】:

我制作了搜索我感兴趣的字符串集的脚本,但我有错误。 我如何解决以下问题:

links = driver.find_elements_by_xpath("xpath")

for x in range(0, len(links)):
    driver.implicitly_wait(2)
    links[x].click()
    try:
        driver.implicitly_wait(3)
        DO something
        driver.back()
        print("Mission completed!!")
    except (ElementNotVisibleException, NoSuchElementException):
        driver.back()
        print("No action")

Error:
selenium.common.exceptions.StaleElementReferenceException: Message: The element reference is stale. Either the element is no longer attached to the DOM or the page has been refreshed.
in line: links[x].click()

【问题讨论】:

    标签: python python-2.7 selenium selenium-webdriver


    【解决方案1】:

    一旦您从列表links 重新定向到新页面元素,您就不能再使用它们了。

    您可以改用以下代码:

    links = [link.get_attribute('href') for link in driver.find_elements_by_xpath("xpath")]
    for link in links:
        driver.get(link)
        # DO something
    

    这应该允许您获取参考列表并循环获取每个页面

    【讨论】:

    • 谢谢你!你教了我很多很好的代码:) 这是最好的方法吗?搜索 20 个链接后,我的网站看起来像 google。
    • 如果只有一个页面有 20 个链接,您可以按原样使用它,但如果您有分页(多个页面,每个页面有 20 个链接),那么您可能会再次循环单击 Next按钮从每个页面附加链接,然后通过提供的循环。一个循环 - 收集链接,一个 - 跟踪参考列表中的链接
    【解决方案2】:

    点击链接有什么作用?如果您在单击后导航到另一个页面,那么迭代中的下一个页面将不再在 DOM 中,实际上变成了stale

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多