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

Selenium(Python)报错:WebDriver无find_element_by_name属性

问题根因

该报错和Chrome浏览器、ChromeDriver的版本匹配无关,核心原因是本地安装的Selenium为4.x版本:Selenium 4正式移除了Selenium 3时代的find_element_by_*系列定位方法,同时直接传入驱动路径初始化webdriver.Chrome()的写法也被标记为废弃,和日志里的DeprecationWarning提示完全对应。
日志中出现的USB设备报错、GPU渲染相关报错、DevTools监听提示均为Chrome启动时的常规冗余输出,不影响自动化逻辑执行,无需额外处理。

修复方法
  • 调整驱动初始化逻辑:使用Service对象封装chromedriver路径,再传入Chrome初始化方法,解决路径传参的废弃警告
  • 替换所有旧版元素定位写法:统一使用find_element()/find_elements()方法,搭配By类指定定位规则,定位到有效元素后即可正常调用send_keys()、submit()等交互方法

修正后的可运行代码如下:

import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

# 替换为本地chromedriver的实际存储路径
service = Service(executable_path="C:/Program Files/Chrome Driver/chromedriver.exe")
driver = webdriver.Chrome(service=service)

driver.get('http://www.google.com/')
time.sleep(5)

# 替换旧版find_element_by_name定位逻辑
search_box = driver.find_element(By.NAME, 'q')
search_box.send_keys('ChromeDriver')
search_box.submit()

time.sleep(5)
driver.quit()

常见旧定位方法和Selenium 4新写法的对应关系可直接套用,方便替换其他同类调用:

  • 旧 find_element_by_id("元素id") → 新 find_element(By.ID, "元素id")
  • 旧 find_element_by_class_name("元素类名") → 新 find_element(By.CLASS_NAME, "元素类名")
  • 旧 find_element_by_xpath("xpath表达式") → 新 find_element(By.XPATH, "xpath表达式")
  • 旧 find_element_by_css_selector("css选择器") → 新 find_element(By.CSS_SELECTOR, "css选择器")
    如果需要批量定位符合规则的多个元素,仅需把方法名中的find_element替换为find_elements即可,对应旧版的find_elements_by_*系列方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 10:24:21