首页 > 解决方案 > Python Web Scraping Html Table 使用漂亮的汤

问题描述

这是我的 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 表并获得上述结果?

标签: pythonhtml-tablebeautifulsoup

解决方案


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

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 += "\n\t" + children_th.text.strip() + "\t" + children_td.text.strip()
print(result)

推荐阅读