如何使用 Selenium 和 Python 提取小计价格

How to extract the Subtotal Price using Selenium and Python

我正在使用 Xpath,但无法提取我需要的信息。

它基本上是价格 - 小计。附上 HTML 图片,下面是我使用的 xpath 代码。我错过了什么?最后,我希望将价格值转化为字符串。

w = driver.find_element_by_xpath('//*[@id="order-summary"]/section/section[3]/div/table/tbody/tr[2]/td/span')
print(w.text())

要打印价格 - 小计文本即 $27.99 您可以使用以下任一方法 :

  • 使用 css_selectorget_attribute("innerHTML"):

    print(driver.find_element(By.CSS_SELECTOR, "td.total-line__price > span.order-summary__emphasis").get_attribute("innerHTML"))
    
  • 使用 xpathtext 属性:

    print(driver.find_element(By.XPATH, "//td[@class='total-line__price']/span[contains(@class, 'order-summary__emphasis')]").text)
    

理想情况下,您需要为 引入 并且您可以使用以下任一项 :

  • 使用 CSS_SELECTORtext 属性:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "std.total-line__price > span.order-summary__emphasis"))).text)
    
  • 使用 XPATHget_attribute("innerHTML"):

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//td[@class='total-line__price']/span[contains(@class, 'order-summary__emphasis')]"))).get_attribute("innerHTML"))
    
  • 注意:您必须添加以下导入:

    从 selenium.webdriver.support.ui 导入 WebDriverWait 从 selenium.webdriver.common.by 导入 从 selenium.webdriver.support 导入 expected_conditions 作为 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