【问题标题】:How do I select the text of the xpath class within the class?如何在类中选择 xpath 类的文本?
【发布时间】:2021-07-10 11:01:58
【问题描述】:

如何获取“a-offscreen”类的文本值?

这是要测试的示例工作代码

from selenium import webdriver

driver = webdriver.Chrome(r'c:\chromedriver\chromedriver.exe')
url = 'https://www.amazon.com/s?k=ipad&ref=nb_sb_noss'
driver.get(url)
title = driver.find_element_by_xpath('.//h2/a').text.strip()
# price = driver.find_element_by_xpath('.//*[contains(@class, "a- 
offscreen")]').text  # does not work
price = driver.find_element_by_xpath('.//*[contains(@class, "a-price- 
whole")]').text  # work
print('title::', title)
print('price::', price)

这是我正在工作的 xml..

我想使用“xpath”获取价格文本值 -> $299.00

这是我正在尝试做的代码。

price = item.find_element_by_xpath('.//*[contains(@class, "a-offscreen")]').text

我无法获得任何价值。

但是,当我在“类”中尝试不同的定价文本时,

 price = item.find_element_by_xpath('.//*[contains(@class, "a-price-whole")]').text

有效(获取价格)

【问题讨论】:

标签: python web-scraping xpath


【解决方案1】:

你需要改变

price = driver.find_element_by_xpath('.//*[contains(@class, "a-offscreen")]').text

price = driver.find_element_by_xpath('.//*[contains(@class, "a-offscreen")]').get_attribute("innerHTML")

【讨论】:

  • 谢谢。有用。我能问你为什么在这种情况下使用 .get_attribute("innerHTML")inner 而不是 ".text" 吗?
  • 它们有隐藏的 html 元素,这些元素在浏览器中呈现然后隐藏。因此,当您尝试获取 text 时 - 浏览器在隐藏的 html 中找不到它,但 innerHTML - 返回带有 html 元素的完整对象。
猜你喜欢
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 2017-03-29
  • 2012-03-03
  • 1970-01-01
  • 2019-08-14
  • 2014-01-12
  • 1970-01-01
相关资源
最近更新 更多