【问题标题】:Python Xpath get the value only from root elementPython Xpath 仅从根元素获取值
【发布时间】:2016-09-18 23:14:44
【问题描述】:

我正在使用 XPath 来废弃一个网页,但我在代码的一部分上遇到了问题:

<div class="description">
   here's the page description
   <span> some other text</span>
   <span> another tag </span>
</div>

我正在使用此代码从元素中获取值:

description = tree.xpath('//div[@class="description"]/text()')

我可以找到我正在寻找的正确 div,但我只想获取文本“这是页面描述”而不是内部跨度标签中的内容

任何人都知道我怎样才能只获取根节点中的文本而不获取子节点中的内容?

【问题讨论】:

  • xpath 表达式不应该包含 spans 的内容,只包含作为 div 的直接子节点的文本节点的内容:["\n here's the page description\n ", '\n ', '\n']

标签: python xpath web-scraping


【解决方案1】:

您当前使用的表达式实际上只会匹配顶级文本子节点。您可以将其包装成 normalize-space() 以清除多余的换行符和空格中的文本:

>>> from lxml.html import fromstring
>>> data = """
... <div class="description">
...    here's the page description
...    <span> some other text</span>
...    <span> another tag </span>
... </div>
... """
>>> root = fromstring(data)
>>> root.xpath('normalize-space(//div[@class="description"]/text())')
"here's the page description"

要获取包含子节点的节点的完整文本,请使用.text_content() 方法:

node = tree.xpath('//div[@class="description"]')[0]
print(node.text_content())

【讨论】:

  • 谢谢,但我认为我的问题不够清楚,我不想从子节点获取内容,只能从根节点获取内容
  • @Dennis 我的错,但你应该很好地使用你目前拥有的表达式 - 它只会匹配顶级文本节点..
猜你喜欢
  • 1970-01-01
  • 2016-01-19
  • 2018-05-25
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 2014-08-09
相关资源
最近更新 更多