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

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

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

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

(会话信息:chrome=80.0.3987.163)

JS widget.

您需要重构您的代码。你的代码模式可能是这样的(当然有不同的 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 的容器可能会变成 re-rendered/reloaded 并且您之前找到的所有元素都会变成 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 循环中一个一个地找到并点击它们