【问题标题】:How to extract all text under the same tag using XPath?如何使用 XPath 提取同一标签下的所有文本?
【发布时间】:2017-07-05 01:05:49
【问题描述】:
<span rel="v:addr">
<span property="v:region">
  <a href="https://tabelog.com/en/tokyo/">
    123
  </a>
</span>
<span property="v:locality">
  <a href="https://tabelog.com/en/tokyo/A1317/A131710/rstLst/">
    456
  </a>
    <a href="https://tabelog.com/en/rstLst/">
      789
    </a>
  10
</span>
<span property="v:street-address">

</span>
</span>

我想提取 span 标签内没有任何空格的文本,并将其作为一个单独的字符串放在末尾。

我想要这个结果:

12345678910

下面是我的代码:

'AddressLocalityJap':"".join(response.xpath('normalize-space(//*[@id="anchor-rd-detail"]/section[1]/table/tbody/tr[4]/td/p[2]/span/span[2]//text()').extract())

【问题讨论】:

    标签: python xml xpath web-crawler text-extraction


    【解决方案1】:

    您可以通过//span/span 获取所有跨度。并使用text_content() 获取每个跨度中的文本。并使用正则表达式替换所有空白字符。

    import re
    from lxml import html
    
    tree = html.fromstring(html_source)
    
    span = tree.xpath("//span/span", smart_strings=0)
    
    text = ''.join([re.sub(r"\s+", '', item.text_content()) for item in span])
    

    【讨论】:

      【解决方案2】:

      纯 XPath 1.0 解决方案

      这个 XPath,

      translate(string(normalize-space()), ' ', '')
      

      会回来

      12345678910
      

      为您的 HTML,根据要求。

      【讨论】:

        猜你喜欢
        • 2023-03-14
        • 2019-07-20
        • 2013-03-16
        • 2020-06-19
        • 2016-09-06
        • 1970-01-01
        • 1970-01-01
        • 2016-03-22
        • 1970-01-01
        相关资源
        最近更新 更多