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()```
合集:
python
分类:
编程相关 / Python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了