为什么在使用此 xpath 语法时会收到已弃用的警告?

Why am I getting a deprecated warning when using this xpath syntax?

我正在使用 selenium 在网页上打印所有产品链接。这是我的代码:

from selenium.webdriver import Chrome
driver_path = PATH = r"C:\Users\David\Desktop\Selenium\chromedriver.exe"

driver = Chrome(executable_path=driver_path)

driver.get('https://www.lazada.com.ph/shop-portable-speakers/?spm=a2o4l.home.cate_2_2.2.239e359dxynAFV'
           )

xpath = '//*[@id="root"]/div/div[2]/div[1]/div/div[1]/div[2]'
link_elements = driver.find_elements_by_xpath(xpath)

links = []
for link_el in link_elements:
    href = link_el.get_attribute("href")
    print (href)
    links.append(href)
driver.quit()

代码运行并打印以下内容:

runfile('C:/Users/David/Desktop/Selenium/untitled1.py', wdir='C:/Users/David/Desktop/Selenium')
C:\Users\David\Desktop\Selenium\untitled1.py:4: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = Chrome(executable_path=driver_path)
C:\Users\David\Desktop\Selenium\untitled1.py:10: DeprecationWarning: find_elements_by_* commands are deprecated. Please use find_elements() instead
  link_elements = driver.find_elements_by_xpath(xpath)
None

关于我在这里做错了什么有什么想法吗?

解决方案

使用 selenium4 作为键 executable_path 已弃用,您必须使用 Service() class 的实例以及 ChromeDriverManager().install() 命令,如下所述。

Pre-requisites 确保:

Selenium 升级到 v4.0.0

pip3 install -U selenium

Python 的 Webdriver 管理器已安装

pip3 install webdriver-manager

Selenium v​​4 兼容代码块

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://www.google.com")

也用

driver.find_elements(By.XPATH, "xpath")

而不是

driver.find_elements_by_xpath(xpath)