繁体   English   中英

Selenium 遍历元素,如果满足一定条件点击元素

[英]Selenium iterate over elements and click on the element if it meets certain condition

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

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

(会话信息:chrome=80.0.3987.163)

JS 小部件。

你需要重构你的代码。 您的代码模式可能是这样的(当然有不同的 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 循环中找到并一一单击它们

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM