WebDriver object has no attribute find_element_by_xpath

在使用Selenium写测试的时候,发现使用xpath查找元素节点,会报错。代码如下:

browser.find_element_by_xpath("/html/body/div[2]/div[1]/div[1]/section[3]/div/form/div/input")

这个时候报的异常信息如下:

AttributeError: 'WebDriver' object has no attribute 'find_element_by_xpath'

我们从官方的升级记录中可以清楚的看到,Selenium 4.3.0版本开始将 find_elent_by_xpath,find_elent_by_id这些方法移除了。具体的详细可参考Selenium版本升级功能记录

Selenium 4.3.0

  • Deprecated findelement_by and findelements_by are now removed (#10712)
  • Deprecated Opera support has been removed (#10630)
  • Fully upgraded from python 2x to 3.7 syntax and features (#10647)
  • Added a devtools version fallback mechanism to look for an older version when mismatch occurs (#10749)
  • Better support for co-operative multi inheritance by utilising super() throughout
  • Improved type hints throughout

那么,替换方法是什么那?

# 查询单个元素
driver.find_element("xpath", '/html/body/div[2]/div[1]/div[1]/section[3]/div/form/div/input')
# 查询多个元素
driver.find_elements("xpath", '/html/body/div[2]/div[1]/div[1]/section[3]/div/form/div/input')

最好的方式是这样的:

from selenium.webdriver.common.by import By
driver.find_element(By.XPATH, '/html/body/div[2]/div[1]/div[1]/section[3]/div/form/div/input')

查看selenium.webdriver.common.by.By源码可以看到,可以支持的参数有:

    ID = "id"
    XPATH = "xpath"
    LINK_TEXT = "link text"
    PARTIAL_LINK_TEXT = "partial link text"
    NAME = "name"
    TAG_NAME = "tag name"
    CLASS_NAME = "class name"
    CSS_SELECTOR = "css selector"

按照上面的方法,”WebDriver’ object has no attribute ‘find_element_by_xpath’” 问题就可以完美解决了。


Selenium 参考链接:github Selenium源码链接

end
  • 作者:kali(作者介绍)
  • 更新时间:2022-07-20 18:09
  • 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)
  • 转载声明:转载站点文章,请附上原文链接
  • 翻译声明:翻译文章会不严谨,请务必附上原文链接
  • 扫描阅读:扫描二维码,手机阅读该文章