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

Python Selenium使用find_element_by_name报错AttributeError求助

解决AttributeError: 'WebDriver' object has no attribute 'find_element_by_name'错误

这个错误是因为你使用的Selenium版本为4.x,该版本已移除find_element_by_name这类旧版元素定位方法,需改用基于By类的新语法。

修改步骤:

  • 新增导入By类:从selenium.webdriver.common.by模块导入By
  • 替换旧的定位代码:将driver.find_element_by_name("q")改为driver.find_element(By.NAME, "q")

修改后的完整代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time

driver=webdriver.Firefox()
driver.get("https://www.python.org")
time.sleep(5)

search_bar = driver.find_element(By.NAME, "q")
search_bar.clear()
search_bar.send_keys("getting started with python")
search_bar.send_keys(Keys.RETURN)

driver.close()

注:不建议降级到Selenium 3.x版本继续使用旧方法,旧版本已停止维护,存在安全隐患。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:54:27