pip install selenium
pip show selenium
Name: selenium
Version: 4.47.0
Summary: Official Python bindings for Selenium WebDriver
Home-page: https://www.selenium.dev
Selenium报错:'WebDriver' object has no attribute 'find_element_by_id'
原因
Selenium 4.3.0及以上版本已经彻底移除 了 find_element_by_id()、find_element_by_xpath()、find_element_by_class_name() 这一类 by_* 的方法。
旧写法已经废弃,不再支持。
❌ 旧写法(会报错)
python
# 已经废弃!
driver.find_element_by_id("username")
driver.find_element_by_xpath("//div")
driver.find_element_by_class_name("box")
driver.find_elements_by_id("xxx")
✅ 新写法(统一使用find_element,配合By类)
需要导入:from selenium.webdriver.common.by import By
python
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
# 通过id查找
elem = driver.find_element(By.ID, "username")
# xpath
elem = driver.find_element(By.XPATH, "//div[@class='item']")
# class name
elem = driver.find_element(By.CLASS_NAME, "box")
# css选择器
elem = driver.find_element(By.CSS_SELECTOR, ".content")
# name属性
elem = driver.find_element(By.NAME, "password")
# 查找多个元素 find_elements (带s)
elems = driver.find_elements(By.CLASS_NAME, "list-item")
By类支持的定位方式
| 定位方式 | 写法 |
|---|---|
| id | By.ID |
| xpath | By.XPATH |
| class | By.CLASS_NAME |
| css选择器 | By.CSS_SELECTOR |
| name属性 | By.NAME |
| 标签名tag | By.TAG_NAME |
| 链接文本 | By.LINK_TEXT |
| 部分链接文本 | By.PARTIAL_LINK_TEXT |
常见坑
- 忘记导入By :直接写
driver.find_element("id","xxx")也可以,不推荐,可读性差
python
# 也能运行,但建议用By常量
driver.find_element("id", "username")
-
网上很多老教程还是旧API,复制过来直接报错。
-
如果你的代码大量是旧方法,不想全部改,可以降级selenium版本(不推荐)
bash
pip install selenium==4.2.0
建议改成新标准写法,新版本有更好的等待、调试能力。
完整示例
python
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://example.com")
# 定位id为search的输入框
search_input = driver.find_element(By.ID, "search")
search_input.send_keys("selenium")
driver.quit()