Selenium - 无法使用 xpath 找到元素

问题描述 投票:0回答:1

我正在用 python 编写一个网络爬虫来获取产品列表的当前补丁版本。我试图通过 XPATH 查找文本,但被告知不存在这样的元素。我尝试过隐式和显式等待长达 60 秒,但仍然没有成功。我看到页面上有一个 iframe,但我尝试访问的文本不在该 iframe 中,所以我认为它不相关。不管怎样,我尝试切换到该 iframe 并找到其中的元素作为测试,但没有成功。

这是我正在尝试抓取的页面

我只是想获取最新的版本号。 我的 XPATH 为:

/html[1]/body[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[5]/div[1]/div[1]/div[1]/div[1]/table[1]/tbody[1]/tr[2]/td[2]/span[1]

这是我正在使用的代码

     url = "https://compatibility.rockwellautomation.com/Pages/ProductReplacement.aspx?crumb=101&restore=1&vid=53216"
        RA_XPATH = "/html[1]/body[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[5]/div[1]/div[1]/div[1]/div[1]/table[1]/tbody[1]/tr[2]/td[2]/span[1]"
        driver.get(url)
        element = WebDriverWait(driver, 60).until(EC.presence_of_all_elements_located((By.XPATH, RA_XPATH)))
        version = driver.find_element(By.XPATH, RA_XPATH)

我可以使用 Rel XPath 找到它,但我想使用 Abs XPath,因为它看起来在多个产品中都是相同的。 以本页为例,Abs XPath 与其他页面相同,但 Rel Xpath 不同

我完全被难住了。
我对这一切都比较陌生,所以感谢您的耐心等待!

python selenium-webdriver web-scraping xpath
1个回答
0
投票

您可以使用不同形式的 XPATH,如下所示:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver import ChromeOptions

options = ChromeOptions()
options.add_argument("--headless=true")
url = "https://compatibility.rockwellautomation.com/Pages/ProductReplacement.aspx?crumb=101&restore=1&vid=53216"

xpath = """//*[@id="TableHeader"]/tbody/tr[2]/td[2]/span"""

with webdriver.Chrome(options) as driver:
    driver.get(url)
    span = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
    print(span.text)

输出:

6.008
© www.soinside.com 2019 - 2024. All rights reserved.