python - 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 表并获得上述结果?
解决方案
我做了以下事情来得到答案。我在这里给出我的解决方案。如果我错了,请纠正我。
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)
推荐阅读
- django - Django注释相关领域的存在
- c# - 将一个参数传递给依赖注入类的构造函数,它也将具有依赖注入参数
- logging - 如何找到 Google Cloud Platform VM 日志?
- c# - _X_AMZN_TRACE_ID 本地调试时未设置环境变量
- swiftui - 在父视图中居中自定义形状的最佳方法?
- reactjs - 有没有办法根据选项的高度设置 react-select 下拉菜单的 maxMenuHeight ?
- flutter - 如何与侧边栏共享底部导航器?
- qt - Qt 是否需要关闭单例 HTML 标签?
- php - 如何在子域中执行规范化?
- graph - 如何创建一个所有条从零开始的堆叠条?