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")
相关推荐
极梦网络无忧7 小时前
OpenClaw 基础使用说明(中文版)
python
codeJinger7 小时前
【Python】操作Excel文件
python·excel
XLYcmy8 小时前
一个针对医疗RAG系统的数据窃取攻击工具
python·网络安全·ai·llm·agent·rag·ai安全
Islucas8 小时前
Claude code入门保姆级教程
python·bash·claude
萝卜白菜。8 小时前
TongWeb7.0相同的类指明加载顺序
开发语言·python·pycharm
赵钰老师8 小时前
【ADCIRC】基于“python+”潮汐、风驱动循环、风暴潮等海洋水动力模拟实践技术应用
python·信息可视化·数据分析
爬山算法9 小时前
MongoDB(80)如何在MongoDB中使用多文档事务?
数据库·python·mongodb
YuanDaima20489 小时前
基于 LangChain 1.0 的检索增强生成(RAG)实战
人工智能·笔记·python·langchain·个人开发·langgraph
RopenYuan10 小时前
FastAPI -API Router的应用
前端·网络·python