【问题标题】:LXML xpath is stripping output of bracketsLXML xpath 正在剥离括号的输出
【发布时间】:2018-01-07 04:48:21
【问题描述】:

我正在尝试废弃 SEC 财务文件中的数据。这是一个示例表的链接:

target_page = 'https://www.sec.gov/Archives/edgar/data/1564408/000156459017022434/R4.htm'

在target_page的源代码中,带有数字输出的表格单元格标记为<td class="num" ...> <a ..>somevalue</a></td>,如果值为负,则写为<td class="num" ...> <a ..>(somevalue)</a></td>(即绝对值包含在()括号中,而不是前面有一个-负号。

我可以通过以下 lxml/requests 脚本轻松提取这些值:

from lxlm.html import fromstring
import requests
page =  requests.get(target_page) 
tree = page.fromstring(page.content)
values = tree.xpath('//td[@class="nump"]/text()')

我的问题:

出于某种原因,tree.xpath('//td[@class="nump"]/text()') 仅提取数字,而不返回任何 () 字符。在示例页面中,我链接的值之一是(461,827),但我的代码将简单地返回461,827

有什么办法解决这个问题?

【问题讨论】:

    标签: python xpath web-scraping lxml


    【解决方案1】:

    这是因为具有负值的单元格具有 num 类,而不是 nump。您可以同时处理这两种情况:

    //td[@class="nump" or @class="num"]/text()
    

    或者:

    //td[starts-with(@class, "num")]/text()
    

    并且,为避免在输出中出现额外的换行符,请使用 .text_content()

    [cell.text_content().strip() for cell in tree.xpath('//td[@class="nump" or @class="num"]')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 2016-03-25
      • 1970-01-01
      • 1970-01-01
      • 2011-12-16
      • 2016-09-01
      相关资源
      最近更新 更多