You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium的find_element_by_*方法报弃用警告如何解决?

Selenium find_element_by_* 弃用警告解决方法

报错原因

DeprecationWarning: find_element_by_ commands are deprecated. Please use find_element()instead

该警告为Selenium 4.0及以上版本的官方规则改动,所有find_element_by_xx系列定位方法已被标记为废弃,后续版本会彻底移除,统一要求使用find_element()方法配合By类完成元素定位。

修正步骤

  1. 代码开头新增By类导入语句
  2. 替换原有元素定位代码的写法
  3. 若需要获取价格文本需调用元素的text属性,直接打印元素对象只会返回WebElement的内存地址

修正后完整代码

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
# 新增导入By类
from selenium.webdriver.common.by import By

chrome_driver_path = Service('C:/Development/chromedriver.exe')
driver = webdriver.Chrome(service=chrome_driver_path)

driver.get('https://www.amazon.com/Instant-Pot-Multi-Use-Programmable-Pressure/dp/B00FLYWNYQ')

# 替换原有定位写法
price = driver.find_element(By.CLASS_NAME, 'a-offscreen')
# 打印价格文本
print(price.text)

driver.quit()

常用定位方式对应写法参考

  • 按class名定位:By.CLASS_NAME
  • 按id定位:By.ID
  • 按xpath定位:By.XPATH
  • 按标签名定位:By.TAG_NAME
  • 按css选择器定位:By.CSS_SELECTOR
  • 按链接文本定位:By.LINK_TEXT / By.PARTIAL_LINK_TEXT

内容的提问来源于stack exchange,提问作者JohnPeter Mwangi Mukuha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:36:03