Selenium 不使用 xpath 提取信息

Selenium not extracting info using xpath

我正在尝试使用 selenium 从 amazon website 中提取一些信息。但是我无法在 selenium 中使用 xpath 抓取该信息。

在下图中,我想提取突出显示的信息。

这是我正在使用的代码

try:
    path = "//div[@id='desktop_buybox']//div[@class='a-box-inner']//span[@class='a-size-small')]"
    seller_element = WebDriverWait(driver, 5).until(
        EC.visibility_of_element_located((By.XPATH, path)))
except Exception as e:
    print(e)

当我 运行 这段代码时,它显示 seller_element = WebDriverWait(driver, 5).until( EC.visibility_of_element_located((By.XPATH, path))) 有错误,但没有说明是什么异常。

我尝试在线查找,发现当 selenium 无法在网页中找到该元素时会发生这种情况。

但我认为我指定的路径是正确的。请帮助我。

提前致谢

[EDIT-1]

这是我得到的异常

Message:
//div[class='a-section a-spacing-none a-spacing-top-base']//span[class='a-size-small a-color-secondary']

XPath 可能是这样的。你可以缩短它。

CSS 选择器可以是等等。

.a-section.a-spacing-none.a-spacing-top-base
.a-size-small.a-color-secondary

亚马逊正在根据您所在的国家/地区更新其内容,因为我点击了您提供的link,在那里我没有找到您正在寻找的元素,因为商品不在印度销售。

简而言之,如果您坐在印度并试图找到您的元素,它不在那里,但当您将位置更改为“美国”时。它出现在那里。

解决方法-更改位置

我认为是xpath表达式不正确。

以下面的元素为例,表示span有两个class:

<span class="a-size-small a-color-secondary">

因此,span[@class='a-size-small') 将不起作用。

除此之外,您可以使用 xpath 作为

//span[contains(@class, 'a-size-small') and contains(@class, 'a-color-secondary')]

或 cssSelector 为

span.a-size-small.a-color-secondary

要打印某个元素的 Amazon.com 发货和销售,您必须引入 for the visibility_of_element_located() and you can use either of the following :

  • 使用 CSS_SELECTORget_attribute():

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.a-section.a-spacing-none.a-spacing-top-base > span.a-size-small.a-color-secondary"))).get_attribute("innerHTML"))
    
  • 使用 XPATHtext 属性:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='a-section a-spacing-none a-spacing-top-base']/span[@class='a-size-small a-color-secondary']"))).text)
    
  • 注意:您必须添加以下导入:

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

You can find a relevant discussion in


结尾

Link 到有用的文档:

  • get_attribute()方法Gets the given attribute or property of the element.
  • text属性returnsThe text of the element.
  • Difference between text and innerHTML using Selenium