【问题标题】:Using xpath to extract only the text being part of the parent node使用 xpath 仅提取作为父节点一部分的文本
【发布时间】:2019-10-28 08:39:10
【问题描述】:

我们怎样才能只选择和提取仅是父节点一部分的文本。这是我正在处理的 HTML。我只需要使用 xpath 提取“$1950”。当我选择父节点并提取其文本内容时,我也会得到其子节点的文本内容,但我只需要父节点的文本内容。

<span class="rentRollup">

 <span class="longText">3 Bedrooms</span>
 <span class="shortText">3 Beds</span>
 $1,950

</span>

我尝试过使用 xpath,但它会打印整个父节点以及子节点数据。

url = 'https://www.apartments.com/214-taylor-st-raleigh-nc/cr6tchd/'
#intializing request headers
ua = UserAgent()
header = {'User-Agent':str(ua.chrome)}
response = requests.get(url, headers=header)
print(response)
byte_data = response.content 
source_code = html.fromstring(byte_data)
name=source_code.xpath("//*[contains(text(), '3 Bedrooms')]/..")
name=name[0].text_content()
print(name)

【问题讨论】:

  • html 代码的结构是否总是使您的目标字符串(在本例中为 $1950)位于具有两个 span 子级的 span 标记内?
  • 是的,总是相同的结构。

标签: python-3.x xpath lxml


【解决方案1】:

试试这个方法:在print(response)之后,将所有内容替换为:

tree = html.fromstring(response.content)
name=tree.xpath("//span[@class='rentRollup']/text()")
name[2].strip()

输出:

'$1,950'

【讨论】:

    【解决方案2】:

    以下 XPath 表达式

    //*[contains(*/text(), '3 Bedrooms')]/text()
    

    将只选择作为感兴趣的父节点的直接子节点的文本节点。但是您仍然需要摆脱空白噪音。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多