0

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

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

(会话信息:chrome=80.0.3987.163)

JS 小部件。

4

1 回答 1

0

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