Python 网页抓取 HTML 表格使用美丽的汤



这是我的HTML表格。

<table class="table_c" id="myd">
<tbody>
<tr class="grp">
<th class="col>MyGrp1</th>
</tr>
<tr class="item">
<th class="col label" scope="row">Item0.1 Header</th>
<td class="col data" data-th="MyGrp1">Item0.1 Value</td>
</tr>
<tr class="grp">
<th class="col label" colspan="2" scope="row">MyGrp</th>
</tr>
<tr class="item">
<th class="col label" scope="row">Item1.1 Header</th>
<td class="col data" >Item1.1 Value</td>
</tr>
<tr class="item">
<th class="col label" scope="row">Item1.2 Header</th>
<td class="col data">Item1.2 Value</td>
</tr>
<tr class="item">
<th class="col label" scope="row">Item1.3 Header</th>
<td class="col data"">Item1.2 Value</td>
</tr>
</tbody>
</table>

我希望表格解析如下

MyGrp1<new line>
<tab char>Item0.1 Header<tab char>Item0.1 Value<new line>
MyGrp2<new line>
<tab char>Item1.1 Header<tab char>Item1.1 Value<new line>
<tab char>Item1.2 Header<tab char>Item1.2 Value<new line>
<tab char>Item1.3 Header<tab char>Item1.3 Value<new line>

我可以获取"tr"或"th"的所有节点。但是我不知道如何逐个节点迭代表。如何抓取 Html 表并获得上述结果?

我为此使用了熊猫

import pandas as pd
import html5lib
string="""<table class="table_c" id="myd">
<tbody>
<tr class="grp">
<th class="col">MyGrp1</th>
</tr>
<tr class="item">
<th class="col label" scope="row">Item0.1 Header</th>
<td class="col data" data-th="MyGrp1">Item0.1 Value</td>
</tr>
<tr class="grp">
<th class="col label" colspan="2" scope="row">MyGrp</th>
</tr>
<tr class="item">
<th class="col label" scope="row">Item1.1 Header</th>
<td class="col data" >Item1.1 Value</td>
</tr>
<tr class="item">
<th class="col label" scope="row">Item1.2 Header</th>
<td class="col data">Item1.2 Value</td>
</tr>
<tr class="item">
<th class="col label" scope="row">Item1.3 Header</th>
<td class="col data"">Item1.2 Value</td>
</tr>
</tbody>
</table>"""
df = pd.read_html(string)
print(df)

输出

[                0              1
0          MyGrp1            NaN
1  Item0.1 Header  Item0.1 Value
2           MyGrp            NaN
3  Item1.1 Header  Item1.1 Value
4  Item1.2 Header  Item1.2 Value
5  Item1.3 Header  Item1.2 Value]

我做了以下事情来得到答案。我在这里给出我的解决方案。如果我错了,请纠正我。

result = ""
for tr in table_t.findAll('tr'):
if 'grp' in tr.get("class"):
for th in tr.findAll('th'):
result += "n" + th.text.strip()
#print(th.text.strip())
elif 'item' in tr.get("class"):
children_th = tr.find("th")
children_td = tr.find("td")
result += "nt" + children_th.text.strip() + "t" + children_td.text.strip()
print(result)

但是我不知道如何逐个节点迭代表。

BeautifulSoupfind_all为您提供了一系列可以循环访问的标记对象。

另请注意,您的 html 表存在合成问题:<th class="col>MyGrp1</th>- 缺少报价<td class="col data"">Item1.2 Value</td>- 双引号

因此,前提是sample是您的 html 表作为刺痛并且它具有有效的 html,以下是您可以执行的示例:

from bs4 import BeautifulSoup as bs
soup = bs(sample, 'lxml-html')
trs = soup.find_all('tr')
group = None # in case there are items before the first group
for tr in trs:
if 'grp' in tr.get('class'):
print(tr.th.text)
elif 'item' in tr.get('class'):
label = tr.th.text
value = tr.td.text
print('{} {}'.format(label, value))

最新更新