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写法。
修复步骤:
- 导入
By类,在代码开头添加:
from selenium.webdriver.common.by import By
- 替换元素查找语句,改用
find_element()方法配合By.XPATH指定定位方式 - 修正异常类的导入路径(若你的
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
相关产品推荐
相关产品推荐

