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

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

提问人: 提问时间:4/24/2022 更新时间:4/24/2022 访问量:365

问:

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

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

关于我在这里做错了什么的任何想法?

python-3.x selenium chrome-web-driver

评论


答:

1赞 Akzy 4/24/2022 #1

溶液

弃用 selenium4 作为键 h 时,您必须使用该类的实例以及命令,如下所述。executable_patService()ChromeDriverManager().install()

先决条件 确保:

Selenium 升级到 v4.0.0

pip3 install -U selenium

已安装 Webdriver Manager for Python

pip3 install webdriver-manager

Selenium v4 兼容代码块

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)

评论

0赞 4/24/2022
看来我已经安装了这些。我认为这与错误有关:DeprecationWarning:find_elements_by_xpath已弃用。请使用 find_elements(by=By.XPATH, value=xpath) 代替 link_elements = driver.find_elements_by_xpath(xpath)。我尝试使用这种语法,但它告诉我变量是未定义的。不确定我是否在这里犯了错误。
0赞 Akzy 4/24/2022
我更新了答案,再试一次。