You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WebDriver无find_element_by_xpath属性错误求助

解决Selenium的AttributeError: 'WebDriver' object has no attribute 'find_element_by_xpath'错误

这个错误的核心原因是你使用的Selenium版本为4.x及以上,该版本已完全移除find_element_by_xpath、find_element_by_id这类旧版元素查找方法,必须使用标准化的新API写法。

修复步骤:

  1. 导入By类,在代码开头添加:
from selenium.webdriver.common.by import By
  1. 替换元素查找语句,改用find_element()方法配合By.XPATH指定定位方式
  2. 修正异常类的导入路径(若你的common.exceptions指向Selenium内置异常,需改为selenium.common.exceptions)

修改后的完整代码片段:

# 确保导入必要的类
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException, ElementClickInterceptedException

while captcha:
    try:
        driver.find_element(By.XPATH, 
            '/html/body/div[3]/div[1]/div[3]/div/div[4]/div/button'
        ).click()
    except (
        NoSuchElementException,
        ElementClickInterceptedException
    ):
        continue
driver.set_window_position(-10000, 0)
print('[!] Running...')
captcha = False

额外说明:

Selenium 4.x后统一使用find_element(By.定位方式, 定位值)和find_elements(By.定位方式, 定位值)的写法,其他定位方式也需同步修改,例如:

  • 旧写法:driver.find_element_by_id('username')
  • 新写法:driver.find_element(By.ID, 'username')

内容的提问来源于stack exchange,提问作者7yago

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 14:23:11