Selenium |AttributeError: ‘WebDriver’ object has no attribute ‘find_element_by_class_name’
出现这个错误是因为你的 selenium 版本太高了,从 selenium 4.3.0 开始,find _ element_by_* 方法已被弃用并删除。
解决方法
- 方法1:
用新版本的方法:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
# 加载谷歌浏览器驱动
path = r'./chromedriver' # 指定驱动存放目录
ser = Service(path)
chrome_options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=ser, options=chrome_options)
...
driver.find_element(By.ID, "id")
driver.find_element(By.NAME, "name")
driver.find_element(By.XPATH, "xpath")
driver.find_element(By.LINK_TEXT, "link text")
driver.find_element(By.PARTIAL_LINK_TEXT, "partial link text")
driver.find_element(By.TAG_NAME, "tag name")
driver.find_element(By.CLASS_NAME, "class name")
driver.find_element(By.CSS_SELECTOR, "css selector")
- 方法2:
将 selenium 降级到 4.2.0,重新安装指定版本即可。
pip install selenium==4.2.0