Python学习笔记:Pandas之read_html、to_html函数

一、read_html函数

Pandas 包中的 read_html() 函数是最简单的爬虫,可以爬取静态网页表格数据。

但只适合于爬取 table 表格型数据,例如:

## 通过F12查看HTML结构
## http://www.air-level.com/air/guangzhou/
<table class="..." id="...">
     <thead>
     <tr>
     <th>...</th>
     </tr>
     </thead>
     <tbody>
        <tr>
            <td>...</td>
        </tr>
        <tr>...</tr>
        <tr>...</tr>
        ...
        <tr>...</tr>
        <tr>...</tr>
    </tbody>
</table>

1.语法解释

import pandas as pd
pd.read_html(io, match='.+', flavor=None, header=None, index_col=None,
            skiprows=None, attrs=None, parse_dates=False, tupleize_cols=None,
            thousands=',', encoding=None, decimal='.', converters=None,
            na_values=None, keep_default_na=True, displayed_only=True)
# 常用的参数
io:url、html文本、本地文件等
flavor:解析器
header:标题行
skiprows:跳过的行
attrs:属性,例如:attrs = {'id':'table'}
parse_dates:解析日期
# 注意:返回的结果是DataFrame组成的list

2.实操

import pandas as pd
data = pd.read_html("http://www.air-level.com/air/guangzhou/", encoding='utf-8', header=0)[0]
'''
       监测站  AQI 空气质量等级     PM2.5      PM10 首要污染物
0  广州番禺大学城   53      良  33 μg/m3  55 μg/m3  PM10
1  广州市八十六中   41      优  21 μg/m3  40 μg/m3   NaN
2  广州广东商学院   37      优  26 μg/m3  36 μg/m3   NaN
3   广州南沙黄阁   31      优   8 μg/m3  30 μg/m3   NaN
4   广州市监测站   30      优  18 μg/m3  29 μg/m3   NaN
'''

Pandas 获取网页表格时,会同时解析所有表格,并存储为 list 格式,因此需要通过切片的方式 table[x] 指定表格。

import pandas as pd
data = pd.read_html("http://www.air-level.com/rank", encoding='utf-8', header=0)[1]
# 即可获取右边表格

3.批量

以新浪财经机构持股汇总数据为例:

# 网址:http://vip.stock.finance.sina.com.cn/q/go.php/vComStockHold/kind/jgcg/index.phtml?p=46
# 共47页
import pandas as pd
data = pd.DataFrame()
for i in range(1, 48):
    url = r"http://vip.stock.finance.sina.com.cn/q/go.php/vComStockHold/kind/jgcg/index.phtml?p={}".format(i)
    print(url)
    data = pd.concat([data, pd.read_html(url)[0]])
    # 爬取并且合并DataFrame
data2 = data.loc[data["证券代码"].notna(),:].reset_index(drop=True)

data.shape # (3688, 9)

二、to_html函数

Pandas 导出数据有 to_csvto_sqlto_excel 等,还可以利用 pd.to_html() 函数将数据存储为 html 格式。

import os
import pandas as pd

os.chdir(r"C:\Users\Hider\Desktop")

data = pd.read_excel(r"C:\Users\Hider\Desktop\test.xlsx")
data.head()
html_table = data.to_html('test.html')

生成 test.html 文件,通过浏览器可打开。

通过 print 打印,可以看到 DataFrame 的内部结构被自动转换为嵌入表格的 <TH><TR><TD> 标签,保留所有内部层级结构。

print(data.to_html())
'''
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>证券代码</th>
      <th>证券简称</th>
      <th>机构数</th>
      <th>机构数变化</th>
      <th>持股比例(%)</th>
      <th>持股比例增幅(%)</th>
      <th>占流通股比例(%)</th>
      <th>占流通股比例增幅(%)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
'''

1.参数

data.to_html('test.html', header=True, index=False, justify='center')

DataFrame.to_html(buf=None, columns=None, col_space=None, 
                  header=True, index=True,na_rep='NaN',
                  formatters=None, float_format=None, sparsify=None,
                  index_names=True,justify=None,
                  bold_rows=True,classes=None, escape=True, max_rows=None,
                  max_cols=None,show_dimensions=False,
                  notebook=False, decimal='.', border=None)

# 参数解释
buf : StringIO-like, 可选
    写入缓冲区。
columns : sequence,可选
    要转化的列的列名;默认值 None 为所有列转化。
col_space : int,可选
    每列的最小宽度。
header : bool,可选
    是否打印列标签,默认为 True。
index : 布尔值,可选
    是否打印索引(行)标签,默认为 True。
na_rep : 字符串,可选
    指定 NAN 的字符串表示形式,默认为 'NaN'。
formatters : 多个单参数函数组成的列表或字典,可选
    格式化程序可按列表的所索引或字典的键名称应用于列元素,默认为 None。
    每个单参数函数的结果必须是一个 unicode 字符串。列表的长度必须等于列数。
float_format: 单参数函数,可选
    用于将列元素设置为浮点数的格式化程序功能,默认为无。
    此单参数函数的结果必须是 unicode 字符串。
sparsify : bool,可选
    默认为 True。输入 False 时,对于具有层次结构索引的 DataFrame,会在每一行打印多重索引。
index_names : bool,可选
    打印索引名称,默认为 True。
line_width : int,可选
    换行符的宽度,默认为不换行。
justify : 列标签对齐方式, 可选
    左右对齐列标签。默认为 None时,使用打印配置中的选项(由 set_option 控制),则右对齐。
bold_rows : bool, 可选
    对横向表格线进行加粗。
classes : CSS类(es)适用于生成的html表, 可选
    默认 None
escape : bool, 可选
    将 "<", ">", "&" 转化成 html 安全序列(??),默认 True。
max_rows : int, 可选
    显示最大行数。
max_cols : int, 可选
    显示最大列数。
decimal : str, 可选
    小数分隔符, 默认为 '.'。
border : int, 可选
    表格外边框宽度,默认为 1,参数为 0 时表格无边框。数值越大外边框越宽。

还可对标题、颜色等进行调整。

2.拓展

结合 Flask 库可实现页面交互展示。

参考链接1:最简单的爬虫:用Pandas爬取表格数据

参考链接2:活用Pandas:将Excel转为html格式

参考链接3:DataFrame.to_html()详解 将数据框 DataFrame 转为 html 表格

posted @ 2021-05-25 18:14  Hider1214  阅读(6109)  评论(0编辑  收藏  举报