Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python从HTML文件读取数据并将数据写入CSV文件?_Python_Html_Pandas_Csv_Beautifulsoup - Fatal编程技术网

如何使用python从HTML文件读取数据并将数据写入CSV文件?

如何使用python从HTML文件读取数据并将数据写入CSV文件?,python,html,pandas,csv,beautifulsoup,Python,Html,Pandas,Csv,Beautifulsoup,我有一个.html文件报告,它由表和通过-失败标准方面的数据组成。因此,我希望使用Python3将这些数据写入.csv文件。 请告诉我如何进行? 例如,数据如下所示: <h2>Sequence Evaluation of Entire Project &nbsp;&nbsp;&nbsp;<em class="contentlink"><a href="#contents">[Contents]</a></em>

我有一个.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>
整个项目的顺序评估
测试序列状态
米制的
百分比
目标
全部的
达到
未实现
测试顺序工作进度
100.0%
100%
24
-
-

假设您知道标题,并且实际上只需要相关的百分比,使用bs4 4.7.1,您可以使用:contains将标题设置为目标标题,然后使用next
td
。您将把HTML从文件读入显示的HTML变量

import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

html = '''
<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>
  '''
soup = bs(html, 'lxml') # 'html.parser' if lxml not installed
header = 'Test Sequence Work Progress'
result = soup.select_one('td:contains("' + header + '") + td').text
df = pd.DataFrame([result], columns = [header])
print(df)
df.to_csv(r'C:\Users\User\Desktop\data.csv', sep=',', encoding='utf-8-sig',index = False )
导入请求
从bs4导入BeautifulSoup作为bs
作为pd进口熊猫
html=“”
整个项目的顺序评估
测试序列状态
米制的
百分比
目标
全部的
达到
未实现
测试顺序工作进度
100.0%
100%
24
-
-
'''
soup=bs(html,'lxml')#'html.parser',如果没有安装lxml
标题='测试序列工作进度'
结果=汤。选择一个('td:contains(“+header+”)+td')。文本
df=pd.DataFrame([result],columns=[header])
打印(df)
df.to_csv(r'C:\Users\User\Desktop\data.csv',sep=',encoding='utf-8-sig',index=False)

什么样的数据?无论如何,您应该看看Python。使用
re
BeautifulSoup
库解析HTML,提取表行和单元格,将其存储在某些数据结构中,最后使用
pandas
或标准Python库写入CSV。很高兴您添加了HTML,但是仍然不清楚您想要从中提取什么。从测试序列工作进度中,我想要“测试序列工作进度”作为列标题,100.0%作为.csv文件中的100%值…@SupratimHaldar请不要建议使用regexps解析HTML-regexps无法正确解析具有任意嵌套结构的语言。此外,您完全不需要panda来编写csv文件,stdlib的csv模块完全可以做到这一点(FWIW panda在引擎盖下使用它,因此您得到的唯一东西是无用的依赖项和开销)。您忘记在那里导入panda:)
将panda作为pd导入
@nexla谢谢。使用jupyter的危险!谢谢你的回答,但我有Bs4版本4.6.0。我建议升级,因为4.7.1中有很多改进和更多功能。我不知道你的版本中是否支持第n种类型,但你可以尝试将选择器更改为。覆盖率td:n种类型(2)谢谢你的回答,我可以打开一个html文件吗(我没有任何URL)所以,如果我打开html,阅读它,然后在for循环中迭代它,这会起作用吗?是的,它会起作用,只需正确输入相对路径!仍然在工作,但在我的要求中,我不需要excel,你能告诉我你为什么用excel写吗?好的!如果您遇到任何问题,请告诉我为什么我需要excel,但将xls转换为csv非常容易
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()