【问题标题】:Selenium iterate over elements and click on the element if it meets certain conditionSelenium 遍历元素并在满足特定条件时单击该元素
【发布时间】:2020-04-16 19:17:53
【问题描述】:

我正在尝试创建一个网络抓取工具,但遇到了问题。我正在尝试迭代小部件左侧的元素,如果名称以“a”开头,我想单击减号并将其移动到右侧。我设法找到了所有元素,但是,一旦执行了向右移动的元素,就在该循环之后,我得到了以下错误。

    StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

(会话信息:chrome=80.0.3987.163)

JS widget.

【问题讨论】:

  • 我也有这个问题。单击后,浏览器的状态发生了变化,现在对元素的引用是“陈旧的”。每次在循环内单击后,尝试获取一个新的元素列表。然后点击下一个元素。
  • 你能把你的代码和页面的链接贴出来

标签: python python-3.x selenium selenium-chromedriver staleelementreferenceexception


【解决方案1】:

您需要重构代码。你的代码模式可能是这样的(当然有不同的 id-s,但由于你没有包含你的代码或页面源,这是我能提供的最好的):

container = driver.find_elements_by_xpath('//*[@class="window_of_elements"]')
elements = container.find_elements_by_xpath('//*[@class="my_selected_class"]')
for e in elements:
    minus_part = e.find_element_by_xpath('//span[@class="remove"]')
    minus_part.click()

当您单击 minus_part 时,您的 elements 的容器可能会重新渲染/重新加载,并且您之前找到的所有元素都会变成 stale

要绕过这个,你应该尝试不同的方法:

container = driver.find_elements_by_xpath('//*[@class="window_of_elements"]')
to_be_removed_count = len(container.find_elements_by_xpath('//*[@class="my_selected_class"]'))
for _ in range(to_be_removed_count):
    target_element = container.find_element_by_xpath('//*[@class="window_of_elements"]//*[@class="my_selected_class"]')
    minus_part = target_element.find_element_by_xpath('//span[@class="remove"]')
    minus_part.click()

所以基本上你应该:

  • 找出你应该找到多少被点击的元素
  • 在 for 循环中找到并一一点击

【讨论】:

    猜你喜欢
    • 2017-07-13
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多