Python爬虫批量爬取网页数据并保存到Excel中

Python爬虫批量爬取网页数据并保存到Excel中,第1张

概述文章目录1、环境准备2、源代码1、环境准备pipinstallrequestspipinstallrepipinstallopenpyxl2、源代码importrequestsimportreimportopenpyxl#要爬取的网页baseurl='https://zhuanlan.zhihu.com/p/357510629'#创建Excel表并写入数据wb=

文章目录1、环境准备2、源代码

1、环境准备
pip install requestspip install repip install openpyxl
2、源代码
import requestsimport reimport openpyxl# 要爬取的网页baseurl = 'https://zhuanlan.zhihu.com/p/357510629'#  创建Excel表并写入数据wb = openpyxl.Workbook()  # 创建Excel对象ws = wb.active  # 获取当前正在 *** 作的表对象# 往表中写入标题行,以列表形式写入!ws.append(['事件名称', '时间', '地点名称', '事件简介'])# 请求头headers = {    'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',    'Connection': 'keep-alive',    'User-Agent': 'Mozilla/5.0 (X11; linux x86_64; rv:60.0) Gecko/20100101 firefox/60.0',    'upgrade-insecure-requests': '1'}content = requests.get(baseurl,headers=headers).content.decode('utf-8')# 事件名称event_name = re.findall(r"<td>事件</td><td>(.+?)</td>",content)print(event_name)# 时间start_time = re.findall(r"<td>时间</td><td>(.+?)</td>",content)print(start_time)# 地点名称area_name = re.findall(r"<td>地点</td><td>(.+?)</td>",content)print(area_name)# 事件简介introduction = re.findall(r"<td>简介</td><td>(.+?)</td>",content)print(introduction)for i in range(len(event_name)):  # 每页25条数据,写入工作表中    ws.append([event_name[i], start_time[i], area_name[i], introduction[i]])wb.save('数据.xlsx')  # 存入所有信息后,保存为filename.xlsx
总结

以上是内存溢出为你收集整理的Python爬虫批量爬取网页数据并保存到Excel中全部内容,希望文章能够帮你解决Python爬虫批量爬取网页数据并保存到Excel中所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1187037.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-03
下一篇2022-06-03

发表评论

登录后才能评论

评论列表(0条)

    保存