python如何获取网页中表格数据

####
#### python如何获取网页中表格数据
####
# -*- coding:utf8-*-
import urllib.request as ur
import pandas as pd

pd.set_option('display.width', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', None)
pd.set_option('display.float_format', '{:,.3f}'.format)
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)

class HtmlDownloader(object):
def download(self, url):
if url is None:
return None
response = ur.urlopen(url)
if response.getcode() != 200:
return None
return response.read()


# 下载指定网页
hd = HtmlDownloader()
html = hd.download(url='http://www.stats.gov.cn/xxgk/sjfb/zxfb2020/202204/t20220419_1829785.html')
# print(html)
# print(type(html))

# 读取网页的表格数据--抓取神器
df = pd.read_html(html) # 如果一个网页只有一张表,那返回的是pandas数据框,如果有多张表,那么返回的是一个列表
# print(type(df[0]))
# 新建文件存放表格数据
writer = pd.ExcelWriter("网页的表格.xlsx")
# ExcelWriter可以看作一个容器
# print(type(writer))
# 一页有多个表格,遍历
cnt = 0
for df1 in df:
cnt = cnt+1
# 写进文件
df1.to_excel(writer, sheet_name='表'+str(cnt), index=False, header=False)
# index为是否写入索引;header为是否写入列名。
# 写完关闭文件
writer.close()
posted @   冀未然  阅读(298)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示