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")
相关推荐
Lyn_Li2 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸6 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学7 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187912 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python