【问题标题】:How to get concatenated child text nodes in lxml如何在lxml中获取连接的子文本节点
【发布时间】:2017-05-08 13:59:18
【问题描述】:

这是HTML 示例:

<div class="wpb_text_column">
    <div class="wpb_wrapper">
      <p style="text-align: center;"><a href="http://somepage1.com">First text part </a></p>
      <p style="text-align: center;"><a href="http://somepage2.com">Second text part </a></p>
      <p style="text-align: center;"><a href="http://somepage3.com">Third text part</a></p>
    </div> 
</div>
<div class="wpb_text_column">
    <div class="wpb_wrapper">
      <p style="text-align: center;"><a href="http://somepage4.com">First text part </a></p>
      <p style="text-align: center;"><a href="http://somepage5.com">Second text part</a></p>
    </div> 
</div>

下面的代码

tree = html.fromstring(html_sample)
tree.xpath('//div[@class="wpb_text_column"]/div[@class="wpb_wrapper"]/p/a/text()')

我可以获得文本值列表

['First text part ', 'Second text part ', 'Third text part', 'First text part ', 'Second text part']

但是,我想从每个 div 中获取所有值作为单个字符串,例如

['First text part Second text part Third text part', 'First text part Second text part']

//div[@class="wpb_text_column"]/div[@class="wpb_wrapper"]/normalize-space()

似乎是exact XPath to solve the problem,但lxml 不支持/normalize-space() 语法:

lxml.etree.XPathEvalError: 无效的表达式

那么如何在lxml 中得到想要的输出呢?

【问题讨论】:

  • lxml 解析器中似乎有一个选项可以在解析时忽略空格:stackoverflow.com/questions/3310614/…
  • 使用tree = html.fromstring(html_sample, parser=etree.XMLParser(remove_blank_text=True)) 会出现错误lxml.etree.XMLSyntaxError: Extra content at the end of the document

标签: xpath lxml lxml.html


【解决方案1】:

使用以下代码解决:

[" ".join(string.text_content().split()) for string in tree.xpath('//div[@class="wpb_text_column"]/div[@class="wpb_wrapper"]')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多