Python爬虫实战:用requests库爬取电商数据并保存到Excel
Python爬虫实战用requests库爬取电商数据并保存到Excel爬虫是 Python 最经典的应用场景之一。本文将从零开始带你用 requests 库爬取电商商品数据并使用 pandas 和 openpyxl 将数据清洗后保存到 Excel 文件。包含完整的反爬处理策略适合新手学习。一、准备工作1.1 安装依赖库首先我们需要安装以下 Python 库pipinstallrequests pandas openpyxl fake-useragent各库的作用requests发送 HTTP 请求获取网页内容pandas数据处理和清洗openpyxl读写 Excel 文件fake-useragent生成随机 User-Agent1.2 项目结构spider_project/ ├── spider.py # 主爬虫脚本 ├── data_clean.py # 数据清洗脚本 ├── requirements.txt # 依赖列表 └── output/ # 输出目录 └── products.xlsx # 最终 Excel 文件二、基础爬虫实现2.1 发送第一个请求我们先从最简单的请求开始importrequests# 发送 GET 请求urlhttps://books.toscrape.com/responserequests.get(url)# 查看响应状态码print(f状态码:{response.status_code})print(f响应长度:{len(response.text)})# 查看部分响应内容print(response.text[:500])2.2 解析 HTML 内容我们使用 Python 内置的html.parser或者更强大的lxml来解析 HTMLfromhtml.parserimportHTMLParserclassProductParser(HTMLParser):def__init__(self):super().__init__()self.products[]self.current_product{}self.captureFalsedefhandle_starttag(self,tag,attrs):attrs_dictdict(attrs)iftagarticleandproduct_podinattrs_dict.get(class,):self.current_product{}iftagh3:self.captureTruedefhandle_data(self,data):ifself.capture:self.current_product[title]data.strip()self.captureFalseparserProductParser()parser.feed(response.text)print(f找到{len(parser.products)}个商品)三、反爬处理策略电商平台通常会有反爬机制我们需要做好以下处理3.1 设置请求头importrequestsfromfake_useragentimportUserAgent uaUserAgent()# 构造完整的请求头headers{User-Agent:ua.random,Accept:text/html,application/xhtmlxml,application/xml;q0.9,*/*;q0.8,Accept-Language:zh-CN,zh;q0.9,en;q0.8,Accept-Encoding:gzip, deflate, br,Connection:keep-alive,Referer:https://books.toscrape.com/,}responserequests.get(url,headersheaders)3.2 请求延迟避免请求过快被识别为爬虫importtimeimportrandomdefcrawl_with_delay(urls):results[]forurlinurls:responserequests.get(url,headersheaders)results.append(response)# 随机延迟 1-3 秒delayrandom.uniform(1,3)print(f等待{delay:.2f}秒...)time.sleep(delay)returnresults3.3 使用代理 IP# 代理池配置proxy_list[http://123.45.67.89:8080,http://98.76.54.32:3128,# 更多代理...]defget_random_proxy():proxyrandom.choice(proxy_list)return{http:proxy,https:proxy}# 使用代理发送请求try:proxyget_random_proxy()responserequests.get(url,headersheaders,proxiesproxy,timeout10)exceptrequests.exceptions.RequestExceptionase:print(f请求失败:{e})3.4 重试机制fromretryingimportretryretry(stop_max_attempt_number3,wait_fixed2000)deffetch_url(url,headersheaders):responserequests.get(url,headersheaders,timeout10)response.raise_for_status()returnresponse四、完整爬虫代码下面是完整的爬虫代码整合了所有反爬策略importrequestsimporttimeimportrandomimportjsonfromfake_useragentimportUserAgentclassECommerceSpider:# 电商数据爬虫def__init__(self):self.uaUserAgent()self.sessionrequests.Session()self.data[]defget_headers(self):# 生成随机请求头return{User-Agent:self.ua.random,Accept:text/html,application/xhtmlxml,application/xml;q0.9,*/*;q0.8,Accept-Language:zh-CN,zh;q0.9,en;q0.8,Connection:keep-alive,}defcrawl_page(self,page_num):# 爬取单页数据urlfhttps://books.toscrape.com/catalogue/page-{page_num}.htmlheadersself.get_headers()try:responseself.session.get(url,headersheaders,timeout10)response.raise_for_status()returnresponse.textexceptrequests.exceptions.RequestExceptionase:print(f第{page_num}页爬取失败:{e})returnNonedefparse_products(self,html):# 解析商品数据fromhtml.parserimportHTMLParserclassBookParser(HTMLParser):def__init__(self):super().__init__()self.books[]self.current{}self.in_titleFalseself.in_priceFalseself.in_ratingFalsedefhandle_starttag(self,tag,attrs):attrs_dictdict(attrs)iftagarticleandproduct_podinattrs_dict.get(class,):self.current{}iftagh3:self.in_titleTrueiftagpandprice_colorinattrs_dict.get(class,):self.in_priceTrueiftagpandstar-ratinginattrs_dict.get(class,):ratingattrs_dict.get(class,).split()[-1]self.current[rating]ratingdefhandle_data(self,data):ifself.in_title:self.current[title]data.strip()self.in_titleFalseifself.in_price:self.current[price]data.strip()self.in_priceFalsedefhandle_endtag(self,tag):iftagarticleandself.current:self.books.append(self.current)self.current{}parserBookParser()parser.feed(html)returnparser.booksdefrun(self,max_pages5):# 运行爬虫print( 开始爬取 )forpageinrange(1,max_pages1):print(f正在爬取第{page}页...)htmlself.crawl_page(page)ifhtml:productsself.parse_products(html)self.data.extend(products)print(f 获取到{len(products)}条数据)# 随机延迟time.sleep(random.uniform(1,3))print(f 爬取完成共{len(self.data)}条数据 )returnself.data# 运行爬虫spiderECommerceSpider()dataspider.run(max_pages5)五、数据清洗爬取到的原始数据通常需要清洗。我们使用 pandas 进行处理importpandasaspddefclean_data(raw_data):# 数据清洗dfpd.DataFrame(raw_data)print(f原始数据量:{len(df)})print(df.head())# 1. 去除重复数据dfdf.drop_duplicates(subset[title])print(f去重后数据量:{len(df)})# 2. 清洗价格字段去除货币符号转换为数值df[price]df[price].str.replace(£,).str.replace(Â,).astype(float)df.rename(columns{price:price_gbp},inplaceTrue)# 3. 评分映射rating_map{One:1,Two:2,Three:3,Four:4,Five:5}df[rating_score]df[rating].map(rating_map)# 4. 添加爬取时间df[crawl_time]pd.Timestamp.now()# 5. 去除空值dfdf.dropna(subset[title,price_gbp])print(f清洗后数据量:{len(df)})returndf# 清洗数据dfclean_data(data)print(df.describe())六、保存到 Excel6.1 基础保存# 最简单的保存方式df.to_excel(output/products.xlsx,indexFalse)print(数据已保存到 output/products.xlsx)6.2 格式化保存使用 openpyxl 进行格式化fromopenpyxlimportWorkbookfromopenpyxl.stylesimportFont,PatternFill,Alignment,Border,Sidefromopenpyxl.utils.dataframeimportdataframe_to_rowsdefsave_to_excel(df,filepath):# 格式化保存到 ExcelwbWorkbook()wswb.active ws.title商品数据# 标题样式header_fontFont(name微软雅黑,size11,boldTrue,colorFFFFFF)header_fillPatternFill(start_color4472C4,end_color4472C4,fill_typesolid)borderBorder(leftSide(stylethin),rightSide(stylethin),topSide(stylethin),bottomSide(stylethin))# 写入数据forrowindataframe_to_rows(df,indexFalse,headerTrue):ws.append(row)# 格式化标题行forcellinws[1]:cell.fontheader_font cell.fillheader_fill cell.alignmentAlignment(horizontalcenter)cell.borderborder# 设置列宽ws.column_dimensions[A].width50# 标题列ws.column_dimensions[B].width15# 价格列ws.column_dimensions[C].width12# 评分列# 添加自动筛选ws.auto_filter.refws.dimensions wb.save(filepath)print(f格式化数据已保存到{filepath})save_to_excel(df,output/products_formatted.xlsx)七、新手注意事项遵守 robots.txt爬取前先查看目标网站的 robots.txt控制请求频率不要请求过快尊重服务器数据仅供学习爬取的数据仅用于学习研究不要商用处理异常网络请求可能失败务必做好异常处理合法合规遵守相关法律法规不要爬取敏感数据八、完整流程总结发送请求 → 获取HTML → 解析数据 → 数据清洗 → 保存Excel | | | | | 设置UA 响应文本 提取字段 去重转换 格式化输出 设置头 编码处理 结构化 空值处理 自动筛选 代理池 超时控制 存储列表 类型转换 列宽设置九、扩展建议使用Scrapy框架处理大型爬虫项目使用Selenium或Playwright处理动态渲染页面使用Redis构建分布式爬虫队列使用数据库MySQL/MongoDB存储大量数据如果这篇文章对你有帮助欢迎点赞、收藏、关注有任何问题欢迎在评论区交流我会及时回复。后续会分享更多 Python 爬虫实战教程敬请期待作者tlyyxjz | 转载请注明出处

相关新闻

LangExtract:面向业务语义的动态文本抽取框架

LangExtract:面向业务语义的动态文本抽取框架

1. 项目概述:为什么传统文本提取正在失效,而LangExtract不是另一个“AI玩具”我做文本数据处理已经十年了。最早用正则表达式从日志里扒IP地址,后来写Python脚本解析PDF表格,再后来搭spaCy流水线做客服工单分类——每一步都踩过坑…

2026/11/6 18:34:04 阅读更多 →
多维聚合实战:银行风控中的五种核心模式

多维聚合实战:银行风控中的五种核心模式

1. 项目概述:为什么多维聚合不是“加个groupby”就完事了?我在银行数据平台组干了八年,从最早用SQL写几十行嵌套子查询做客户分层,到后来在Spark上跑PB级交易流水,再到如今带团队设计实时风控指标引擎——所有这些活儿…

2026/11/8 10:40:07 阅读更多 →
大模型API实战指南:GPT、Gemini与Llama技术选型与工程实践

大模型API实战指南:GPT、Gemini与Llama技术选型与工程实践

如果你最近在关注大模型动态,可能会被各种"GPT-5.6"、"Gemini 3.5 Pro"的消息搞得一头雾水。这些看似"最新"的模型版本,实际上很多都是社区讨论中的非官方信息,甚至包含误导性内容。今天这篇文章,我…

2026/11/12 21:30:48 阅读更多 →

最新新闻

Electron桌面应用开发实战:从环境搭建到打包发布全流程

Electron桌面应用开发实战:从环境搭建到打包发布全流程

做前端这些年,我大部分时间都在跟浏览器标签页打交道,直到第一次把桌面应用跑起来,才发现原来自己一直被限制在地址栏和刷新按钮围起来的框框里。Electron这个词,最开始是在某段时间频繁出现在同事的讨论里,一个用HTML…

2026/11/13 5:13:25 阅读更多 →
滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

简介:亚太天能T109滑盖智能锁产品说明书是一份PDF格式的官方技术文档,主要面向智能锁安装人员、终端用户及售后维护者,帮助快速掌握产品安装、配置与常见故障处理。全包仅1个PDF文件,大小4.37MB,内容结构清晰&#xff…

2026/11/13 5:13:25 阅读更多 →
PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

上个月我在调试一台高速AGV的驱动系统,整车要求空载跑到8m/s,电机转速已经拉到额定点,驱动器的输出电压也顶到了母线电压极限附近。再往上踩速度指令,转速纹丝不动,三相电流反而开始震荡。那会儿我的第一反应就是&…

2026/11/13 5:13:25 阅读更多 →
C++核心知识点:从内存管理到STL的实战指南

C++核心知识点:从内存管理到STL的实战指南

C 这门语言我前前后后折腾了十几年,用它写过嵌入式驱动、做过游戏服务端,也搭过基础组件库。每次看到新人一头扎进"C 核心知识点"这个搜索词,我其实挺感慨的——这门语言的难点从来不是语法多,而是知识点之间的耦合太深…

2026/11/13 22:08:41 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

T109滑盖智能锁怎么装?安装调试与故障排查全攻略

简介:亚太天能T109滑盖智能锁产品说明书以PDF格式发布,适合智能锁用户、安装人员与售后维修人员阅读。内容围绕T109系列指纹密码刷卡锁展开,先介绍前面板、后面板、锁体、机械钥匙、电池盒盖等部件名称与功能,再给出完整安装步骤&…

2026/11/12 18:22:25 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

LLM知识降熵:从信息垄断到理解权下放

你有没有过这种经历:翻开源码注释、论文摘要或者一份专业报告,每个字都认识,连在一起却像天书。想找人聊聊,身边要么没人懂,要么懂的懒得跟你解释。后来我试着把同一段内容丢给一个大语言模型,几秒钟之后&a…

2026/11/13 5:13:25 阅读更多 →

日新闻

周新闻

月新闻