
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 | 转载请注明出处