如何在Python中解析.TXT格式的HTML文件(非制表符)?

时间:2019-04-05 00:45:17

标签: python html text beautifulsoup

我在编程中遇到了困扰我的问题。

我正在尝试访问存储在大量旧的HTML格式的另存为文本文件中的数据。但是,保存HTML代码时会丢失其缩进,制表符,层次结构,无论您希望调用什么。可以在下面找到一个示例。

......

<tr class="ro">
<td class="pl " style="border-bottom: 0px;" valign="top"><a class="a" href="javascript:void(0);" onclick="top.Show.showAR( this, 'defref_us-gaap_RevenueFromContractWithCustomerExcludingAssessedTax', window );">Net sales</a></td>
<td class="nump">$ 123,897<span></span>
</td>
<td class="nump">$ 122,136<span></span>
</td>
<td class="nump">$ 372,586<span></span>
</td>
<td class="nump">$ 360,611<span></span>
</td>
</tr>
<tr class="re">
<td class="pl " style="border-bottom: 0px;" valign="top"><a class="a" href="javascript:void(0);" onclick="top.Show.showAR( this, 'defref_us-gaap_OtherIncome', window );">Membership and other income</a></td>
<td class="nump">997<span></span>
</td>
<td class="nump">1,043<span></span>
</td>
<td class="nump">3,026<span></span>
</td>
<td class="nump">3,465<span></span>
</td>
</tr>
<tr class="rou">
<td class="pl " style="border-bottom: 0px;" valign="top"><a class="a" href="javascript:void(0);" onclick="top.Show.showAR( this, 'defref_us-gaap_Revenues', window );">Total revenues</a></td>
<td class="nump">124,894<span></span>
</td>
<td class="nump">123,179<span></span>
</td>
<td class="nump">375,612<span></span>
</td>
<td class="nump">364,076<span></span>
</td>
</tr>

我通常会在这里雇用Beautiful Soup,然后开始以这种方式解析数据,但是由于技术上这里没有层次结构,因此我没有找到一个好的工作流程。我不能告诉BS去查看文档本身以外的东西,这是巨大的,而且可能太耗时(请参阅下一条语句)。

我还需要找到一个彻底的解决方案,而不是快速解决方案,因为我有数百个(即使不是数千个)这些相同的HTML到文本文件也要解析。

所以我的问题是,如果我想在所有文件中返回“会员资格和其他收入”的第一个数字(在本例中为997),我该怎么做? strong>

可以在此处找到两个示例文件:

https://www.sec.gov/Archives/edgar/data/1800/0001104659-18-065076.txt)(https://www.sec.gov/Archives/edgar/data/1084869/0001437749-18-020205.txt


编辑-4/16

感谢大家的回覆!我已经写了一些代码来返回我要寻找的标签。

import requests
from bs4 import BeautifulSoup

data = requests.get('https://www.sec.gov/Archives/edgar/data/320193/0000320193-18-000070.txt')

# load the data
soup = BeautifulSoup(data.text, 'html.parser')

# get the data
for tr in soup.find_all('tr', {'class':['rou','ro','re','reu']}):
    db = [td.text.strip() for td in tr.find_all('td')]
    print(db)

问题在于有大量退货,而且大多数都没有使用。有没有一种方法可以基于这些标签的祖父母进行过滤?我已经尝试过使用头,标题,正文等与上述相同的方法,但是我无法完全让BS来识别FILENAME。

<DOCUMENT>
<TYPE>XML
<SEQUENCE>14
**<FILENAME>R2.htm**
<DESCRIPTION>IDEA: XBRL DOCUMENT
<TEXT>
<html>
<head>
<title></title>
.....removed for brevity
</head>
<body>
.....removed for brevity
<td class="text">&#160;<span></span>
</td>
.....removed for brevity
</tr>

1 个答案:

答案 0 :(得分:1)

请注意,HTML并不关心缩进。如果您确实希望这样做,那么它们可能全部在同一行上,并且之间没有空格。 HTML解析器将仅查看标记的结构。

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
soup.find_all['<tag you are looking for>'][0]