python - 如何从 HTML 文件中读取数据并使用 python 将数据写入 CSV 文件?
问题描述
我有一个 .html 文件报告,其中包含表格和通过失败标准方面的数据。所以我希望使用 Python3 将这些数据写入 .csv 文件。请建议我如何进行?例如,数据将是这样的:
<h2>Sequence Evaluation of Entire Project <em class="contentlink"><a href="#contents">[Contents]</a></em> </h2>
<table width="100%" class="coverage">
<tr class="nohover">
<td colspan="8" class="tableabove">Test Sequence State</td>
</tr>
<tr>
<th colspan="2" style="white-space:nowrap;">Metric</th>
<th colspan="2">Percentage</th>
<th>Target</th>
<th>Total</th>
<th>Reached</th>
<th>Unreached</th>
</tr>
<tr>
<td colspan="2">Test Sequence Work Progress</td>
<td>100.0%</td>
<td>
<table class="metricbar">
<tr class="borderX">
<td class="white"></td>
<td class="target"></td>
<td class="white" colspan="2"></td>
</tr>
<tr>
<td class="covreached" width="99%"></td>
<td class="target" width="1%"></td>
<td class="covreached" width="0%"></td>
<td class="covnotreached" width="0%"></td>
</tr>
<tr class="borderX">
<td class="white"></td>
<td class="target"></td>
<td class="white" colspan="2"></td>
</tr>
</table>
</td>
<td>100%</td>
<td>24</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
解决方案
import csv
from bs4 import BeautifulSoup
out = open('out.csv', 'w', encoding='utf-8')
path="my.html" #add the path of your local file here
soup = BeautifulSoup(open(path), 'html.parser')
for link in soup.find_all('p'): #add tag whichyou want to extract
a=link.get_text()
out.write(a)
out.write('\n')
out.close()
推荐阅读
- javascript - 如何将数据传递给另一个函数 | 要求('请求')
- windows - 如何从 RichEdit 中清除“临时”(tomApplyTmp) 格式?
- docker - docker compose 卷类型 - 绑定与卷
- redis - 在 Airflow 的不同机器上运行一个 DAG 的多个任务
- java - 发生断言错误后 Chrome 不会退出
- javascript - 防止重复产品从购物车中删除
- python - 开始 Space Invaders Code 并在其中的一部分需要帮助
- java - Java Inflater 有时会无限循环
- java - 用值组合 int 键
- python-2.7 - 如何使用 HTTPS 在 CherryPy WSGI 服务器(Cheroot)上运行 Flask 应用程序?