LXML xpath 正在剥离括号的输出
LXML xpath is stripping output of brackets
我正试图从美国证券交易委员会的财务文件中获取数据。这是一个 link 示例 table:
target_page = 'https://www.sec.gov/Archives/edgar/data/1564408/000156459017022434/R4.htm'
在target_page的源代码中,一个带有数字输出的table单元格用<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()')
只提取数字,而不是 returning 任何 ()
字符。在示例页面中,我 linked 的值之一是 (461,827)
,但我的代码将简单地 return 461,827
.
有什么办法可以解决这个问题?
这是因为具有负值的单元格具有 num
class,而不是 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"]')]
我正试图从美国证券交易委员会的财务文件中获取数据。这是一个 link 示例 table:
target_page = 'https://www.sec.gov/Archives/edgar/data/1564408/000156459017022434/R4.htm'
在target_page的源代码中,一个带有数字输出的table单元格用<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()')
只提取数字,而不是 returning 任何 ()
字符。在示例页面中,我 linked 的值之一是 (461,827)
,但我的代码将简单地 return 461,827
.
有什么办法可以解决这个问题?
这是因为具有负值的单元格具有 num
class,而不是 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"]')]