selenium定位元素报错:‘WebDriver‘ object has no attribute ‘find_element_by_id‘

Selenium更新到 4.x版本后,以前的一些常用的代码的语法发生了改变

复制代码
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.baidu.com')
input = browser.find_element_by_id(By.ID,'kw')
input.send_keys('Python')

目标:希望通过 selenium 模拟在 "百度" 上 输入关键词搜索

思路:通过对网页的源代码分析(进入www.baidu.com,右键并检查则可看其HTML源代码),定位到搜索框的属性id="kw"

报错:

复制代码
AttributeError: 'WebDriver' object has no attribute 'find_element_by_id'

报错原因:

selenium 更新到 4.x 之后,很多api发生了变化

解决方案:

复制代码
#input = browser.find_element_by_id('kw')
# 替换为
input = browser.find_element(By.ID,'kw')

当然最最推荐的还是去官方查看文档:https://www.selenium.dev/documentation/webdriver/getting_started/first_script/

参考资料:

https://blog.csdn.net/m0_49076971/article/details/126233151

https://www.selenium.dev/documentation/webdriver/getting_started/first_script/

相关推荐
螺丝钉tina14 小时前
[Playwright] [02]常用命令与调试:Debug UI、Mode和 Trace Viewer
开发语言·javascript·测试工具·ui·自动化
梧桐1682 天前
14天、31个缺陷、28个测试脚本—用 Claude Code 完成第三方软件测试
人工智能·测试工具
mewowaBc2 天前
postman使用细则
测试工具·postman·偏差
光影6272 天前
Unittest单元测试基础速记
测试工具·单元测试·json·测试覆盖率
xie881018023 天前
正则里的点号不匹配换行:多行模式的开关
运维·服务器·测试工具
2601_967987374 天前
Python在自动化测试中有哪些应用?
python自动化测试·selenium·appium·pytest·性能测试
东舟技术4 天前
从人工目检到AI视觉:智能座舱瞬态故障的自动化捕获与溯源
功能测试·测试工具·自动化
小猿A5 天前
【2026最新】Apifox下载、配置、实战教程(附官网安装包)
测试工具
泽众云测试6 天前
泽众软件与广州华南检验检测中心签约,PerformanceRunner性能测试工具助力第三方测评机构性能检测能力升级
软件测试·测试工具·性能测试
@zulnger6 天前
Charles抓包工具
测试工具