Selenium Python无法使用find_element_by_id,仅显示find_element方法求指导
解决Selenium中find_element()/find_elements()替代旧定位方法的问题
为什么看不到find_element_by_id等方法?
你使用的是Selenium 4.0+版本,从这个版本开始,官方移除了find_element_by_id()、find_element_by_xpath()等旧版定位方法,统一保留find_element()和find_elements()两个核心方法。
find_element()和find_elements()的使用方式
1. 前置准备
需要先导入By类来指定定位方式:
from selenium.webdriver.common.by import By
2. 核心语法
find_element(定位方式, 定位值):返回匹配到的第一个元素,找不到元素会抛出NoSuchElementExceptionfind_elements(定位方式, 定位值):返回匹配到的所有元素组成的列表,找不到元素会返回空列表
3. 对应旧方法的替代示例
| 旧版方法 | 新版find_element()写法 |
|---|---|
find_element_by_id("xxx") | driver.find_element(By.ID, "xxx") |
find_element_by_name("xxx") | driver.find_element(By.NAME, "xxx") |
find_element_by_xpath("xxx") | driver.find_element(By.XPATH, "xxx") |
find_element_by_css_selector("xxx") | driver.find_element(By.CSS_SELECTOR, "xxx") |
find_element_by_class_name("xxx") | driver.find_element(By.CLASS_NAME, "xxx") |
find_element_by_link_text("xxx") | driver.find_element(By.LINK_TEXT, "xxx") |
4. find_elements()实际使用示例
比如获取页面中所有class为"product-item"的元素并遍历:
product_items = driver.find_elements(By.CLASS_NAME, "product-item") for item in product_items: print(item.get_attribute("title"))
额外提示
如果非要用旧版方法,可以把Selenium降级到3.x版本,但不推荐——官方已停止旧版维护,新版方法的定位逻辑更统一规范。
内容的提问来源于stack exchange,提问作者Sarthak Bhatore
相关产品推荐
相关产品推荐

