首页 > 解决方案 > 如何从 HTML 文件中读取数据并使用 python 将数据写入 CSV 文件?

问题描述

我有一个 .html 文件报告,其中包含表格和通过失败标准方面的数据。所以我希望使用 Python3 将这些数据写入 .csv 文件。请建议我如何进行?例如,数据将是这样的:

<h2>Sequence Evaluation of Entire Project &nbsp;&nbsp;&nbsp;<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>

标签: pythonhtmlpandascsvbeautifulsoup

解决方案


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()  

推荐阅读