AttributeError: ‘WebDriver‘ object has no attribute ‘find_element_by_id‘

AttributeError: 'WebDriver' object has no attribute 'find_element_by_id'

在Selenium 4及以上版本中,find_element_by_* 和 find_elements_by_* 这类方法已经被弃用并移除了,所以使用会报错:

AttributeError: 'WebDriver' object has no attribute 'find_element_by_id'

从Selenium 4开始,推荐使用新的方法find_element()和find_elements()结合By类来定位元素。

python 复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

# 1. 按 id 定位
element = driver.find_element(By.ID, "element-id")

# 2. 按 name 定位
element = driver.find_element(By.NAME, "element-name")

# 3. 按 class 定位
element = driver.find_element(By.CLASS_NAME, "element-class")

# 4. 按 tag 标签定位
element = driver.find_element(By.TAG_NAME, "input")

# 5. 按链接文本定位
element = driver.find_element(By.LINK_TEXT, "Click Here")

# 6. 按部分链接文本定位
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Click")

# 7. 按 xpath 定位
element = driver.find_element(By.XPATH, "//div[@id='element-id']")

# 8. 按 css 选择器定位
element = driver.find_element(By.CSS_SELECTOR, "#element-id .element-class")
相关推荐
love530love21 小时前
LiveTalking 数字人项目 Windows 部署完全指南(EPGF 架构)
人工智能·windows·python·架构·livetalking·epgf
遇事不決洛必達21 小时前
【Python基础】GIL 锁是什么及其对爬虫的影响
爬虫·python·线程·进程·gil锁
CryptoPP1 天前
快速对接东京证券交易所API数据:实战指南与代码示例
开发语言·人工智能·windows·python·信息可视化·区块链
探物 AI1 天前
把 MambaOut 塞进 YOLOv11:会有什么样的反应
python·yolo·计算机视觉
如竟没有火炬1 天前
最大矩阵——单调栈
数据结构·python·线性代数·算法·leetcode·矩阵
阳区欠1 天前
【LangChain】LLM基础介绍
开发语言·python·langchain
Cosolar1 天前
保姆级 CrewAI 教程:从零构建多智能体协作系统
人工智能·python·架构
GDAL1 天前
使用 uv 管理 Python 版本
python·uv·版本
真实的菜1 天前
Redis 从入门到精通(十二):典型业务场景实战 —— 排行榜、限流器、秒杀系统、Session 共享
数据库·redis·python
cup111 天前
[开源] Meta Assistant / 告别命令行,我为一堆 Python 脚本做了一个 Windows 任务栏的“家”
windows·python·工具·nuitka·脚本运行