首页 > 解决方案 > 注册机器人

问题描述

嗨,我想写注册机器人。

我在 python 中使用 selenium,一开始我遇到了以下问题。

elems = driver.find_elements_by_xpath("//a[@href]")
    for elem in elems:
        elem_ = elem.get_attribute("href")
        regex = re.compile('signup')
        match = re.search(regex, elem_)
        if match:
            print(elem_)
            elem.click()

这样我就可以找到注册链接,但是当我尝试单击它时,它给了我:

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

我是否严重访问了该元素?如何对 find_elements_by_something 创建的列表中的元素执行单击功能?

标签: pythonseleniumautomation

解决方案


您执行click函数的方式是正确的:find_elements函数返回一个WebElements列表,然后您调用其中一个元素的click函数。问题出在其他地方。

文档: 过时元素引用异常

在以下两种情况之一中会引发过时的元素引用异常,第一种比第二种更常见:

该元素已被完全删除。

该元素不再附加到 DOM。

如您所见,当 selenium 无法在 DOM 结构中定位元素时,会引发异常。

此问题的通用解决方案不存在,因为它取决于您正在处理的网页。

一般这类问题发生在动态页面中,顾名思义,DOM结构是动态生成的。

看起来很简单,一个常见的解决方案是再试一次,只需将它包围在一个try块中并重新执行代码:

from selenium.common.exceptions import StaleElementReferenceException

try:
    ...
except StaleElementReferenceException:
    ...

在最坏的情况下,如果您必须执行的唯一操作是按钮 click(),您可以通过ActionChain解决 DOM 通过坐标移动到元素的问题。

from selenium.webdriver.common.action_chains import ActionChains

elem = driver.find_element(By.TAG_NAME, 'body')
ac = ActionChains(driver)
ac.move_to_element(elem).move_by_offset(x_offset, y_offset).click().perform()

推荐阅读