【问题标题】:BeautifulSoup find text through 2 terms in html tag - Python 3BeautifulSoup 通过 html 标签中的 2 个术语查找文本 - Python 3
【发布时间】:2017-05-17 10:52:18
【问题描述】:

我正在尝试从 html 文件中抓取一些文本,但是我需要两种类型的文本,它们的标签中的一个术语 (contextref) 彼此不同,例如:

1)<ix:nonfraction contextref="cfwd_30_04_2016" name="ns5:TangibleFixedAssets" unitref="GBP" decimals="0" format="ixt2:numdotdecimal" scale="0" xmlns:ix="http://www.xbrl.org/2008/inlineXBRL">180,649</ix:nonfraction>

2)<ix:nonfraction contextref="cfwd_30_04_2015" name="ns5:TangibleFixedAssets" unitref="GBP" decimals="0" format="ixt2:numdotdecimal" scale="0" xmlns:ix="http://www.xbrl.org/2008/inlineXBRL">200,395</ix:nonfraction>

目前我查找文本的代码是:var1=(soup.find('ix:nonfraction',{'name':'uk-gaap:{}'.format(variable)}).text),上面的示例给出:180,649。

为了让我能够同时获得这两个值,我需要另一个变量来包含另一个术语以及name,(作为contextref)我尝试了不同的组合,但似乎无法使其工作。

任何帮助都会很棒,谢谢

【问题讨论】:

  • 这是 xml 代码吗?并发布你想要的输出。
  • 不,文件都是.html 理想的输出是var1 包含来自第一个标签的文本文件 = 180,649 和 var2 来自第二个标签 = 200,395。可能值得注意的是这两个标签不在同一个头标签下

标签: python html python-3.x beautifulsoup html-parsing


【解决方案1】:
import bs4

html = '''<ix:nonfraction contextref="cfwd_30_04_2016" name="ns5:TangibleFixedAssets" unitref="GBP" decimals="0" format="ixt2:numdotdecimal" scale="0" xmlns:ix="http://www.xbrl.org/2008/inlineXBRL">180,649</ix:nonfraction>
<ix:nonfraction contextref="cfwd_30_04_2015" name="ns5:TangibleFixedAssets" unitref="GBP" decimals="0" format="ixt2:numdotdecimal" scale="0" xmlns:ix="http://www.xbrl.org/2008/inlineXBRL">200,395</ix:nonfraction>'''

soup = bs4.BeautifulSoup(html, 'lxml')
var1, var2 = [i.text for i in soup.find_all('ix:nonfraction')]

出来:

('180,649', '200,395')

您可以在find_all() 中使用contextref 作为关键字:

soup.find_all('ix:nonfraction', contextref=True)

这意味着过滤具有contextref属性的标签。

【讨论】:

  • 因为 html 不仅仅包含该标签,因此我得到了大量带有 contextref 的标签:Traceback (most recent call last): File "test.py", line 58, in &lt;module&gt; var1, var2 = [i.text for i in soup.find_all('ix:nonfraction')] ValueError: too many values to unpack (expected 2) 理想情况下,我需要一个代码来查找特定的ix,@987654329 @ 和 contextref
猜你喜欢
  • 2019-10-08
  • 1970-01-01
  • 2013-09-18
  • 2017-05-04
  • 1970-01-01
  • 2020-12-07
  • 2010-10-26
  • 2014-05-09
  • 2013-01-11
相关资源
最近更新 更多