python网络请求库实战 - urllib与requests深度解析
文章目录1.1 urllib - Python内置请求库基础使用添加请求头带参数的GET请求POST请求异常处理1.2 requests - 爬虫开发的首选库安装基础请求请求参数的几种传递方式请求头设置Cookie处理代理配置超时和重试响应数据处理1.3 实战综合运用GET/POST请求1.1 urllib - Python内置请求库基础使用urllib不需要安装直接导入使用。虽然不如requests简洁但了解它能帮助你理解HTTP请求的底层逻辑。fromurllib.requestimporturlopen,Requestfromurllib.parseimporturlencode,quotefromurllib.errorimportURLError,HTTPError# 最简单的GET请求withurlopen(https://www.python.org)asresponse:htmlresponse.read().decode(utf-8)print(html[:500])# 打印前500个字符添加请求头不加请求头的请求很容易被识别为爬虫。urlhttps://example.comheaders{User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36}# 使用Request对象添加请求头reqRequest(url,headersheaders)withurlopen(req,timeout10)asresponse:htmlresponse.read().decode(utf-8)带参数的GET请求base_urlhttps://example.com/searchparams{keyword:Python爬虫,page:1,size:20}# urlencode将字典转为查询字符串query_stringurlencode(params)full_urlf{base_url}?{query_string}print(full_url)# https://example.com/search?keywordPython%E7%88%AC%E8%99%ABpage1size20POST请求urlhttps://example.com/logindata{username:test,password:123456}# POST数据需要编码为bytespost_dataurlencode(data).encode(utf-8)reqRequest(url,datapost_data,headersheaders)withurlopen(req)asresponse:resultresponse.read().decode(utf-8)print(result)异常处理try:responseurlopen(https://example.com,timeout5)exceptHTTPErrorase:print(fHTTP错误:{e.code}-{e.reason})exceptURLErrorase:print(fURL错误:{e.reason})exceptExceptionase:print(f其他错误:{e})1.2 requests - 爬虫开发的首选库安装pipinstallrequests基础请求requests的API设计非常直观大大简化了HTTP请求的代码量。importrequests# GET请求responserequests.get(https://www.python.org)print(response.status_code)# 200print(response.encoding)# utf-8print(response.text[:200])# HTML内容# POST请求responserequests.post(https://example.com/login,data{user:test})# 其他请求方法requests.put(https://api.example.com/resource/1,json{name:new_name})requests.delete(https://api.example.com/resource/1)请求参数的几种传递方式# 方式1: params参数(GET请求)params{keyword:Python,page:2}responserequests.get(https://example.com/search,paramsparams)print(response.url)# https://example.com/search?keywordPythonpage2# 方式2: data参数(POST表单)data{username:user,password:pass}responserequests.post(https://example.com/login,datadata)# 方式3: json参数(POST JSON)payload{action:search,keyword:Python}responserequests.post(https://api.example.com/data,jsonpayload)# 方式4: 请求体raw数据importjson responserequests.post(https://api.example.com/data,datajson.dumps(payload),headers{Content-Type:application/json})请求头设置headers{User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36,Accept:application/json, text/plain, */*,Accept-Language:zh-CN,zh;q0.9,Referer:https://example.com,Connection:keep-alive}responserequests.get(https://example.com/api/data,headersheaders)常见User-Agent列表importrandom USER_AGENTS[Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36,Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36,Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0,Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36,]defget_random_ua():returnrandom.choice(USER_AGENTS)headers{User-Agent:get_random_ua()}responserequests.get(url,headersheaders)Cookie处理# 方式1: 直接在headers中设置headers{Cookie:session_idabc123; user_id12345; tokenxyz789}responserequests.get(url,headersheaders)# 方式2: 通过cookies参数cookies{session_id:abc123,user_id:12345}responserequests.get(url,cookiescookies)# 方式3: 使用Session自动管理Cookie(最推荐)sessionrequests.Session()session.headers.update({User-Agent:Mozilla/5.0 ...})# 第一次请求: 登录login_data{username:test,password:123456}session.post(https://example.com/login,datalogin_data)# 后续请求: 自动携带Cookieresponsesession.get(https://example.com/user/orders)profilesession.get(https://example.com/user/profile)代理配置代理是突破IP封禁的常用方法。# 单一代理proxies{http:http://127.0.0.1:7890,https:http://127.0.0.1:7890}responserequests.get(url,proxiesproxies)# 带用户名密码的代理proxies{http:http://username:passwordproxy.example.com:8080,https:http://username:passwordproxy.example.com:8080}# 随机代理池PROXY_LIST[http://proxy1.example.com:8080,http://proxy2.example.com:8080,http://proxy3.example.com:8080,]defget_random_proxy():iprandom.choice(PROXY_LIST)return{http:ip,https:ip}responserequests.get(url,proxiesget_random_proxy())超时和重试importtime# 设置超时try:responserequests.get(url,timeout10)# 10秒超时# timeout(连接超时, 读取超时)responserequests.get(url,timeout(5,15))# 连接5秒,读取15秒exceptrequests.Timeout:print(请求超时)# 自动重试封装deffetch_url(url,headersNone,max_retries3,delay2):forattemptinrange(1,max_retries1):try:responserequests.get(url,headersheaders,timeout10)response.raise_for_status()# 非2xx状态码抛出异常returnresponseexceptrequests.Timeout:print(f超时,第{attempt}次重试)exceptrequests.HTTPErrorase:print(fHTTP错误{e.response.status_code})ife.response.status_codein[403,404]:returnNone# 这类错误重试无意义exceptrequests.RequestExceptionase:print(f请求异常:{e})ifattemptmax_retries:time.sleep(delay*attempt)# 递增延迟returnNone响应数据处理responserequests.get(https://example.com)# 自动检测编码print(response.encoding)# 检测到的编码print(response.apparent_encoding)# 更准确的编码检测# 设置编码解决乱码response.encodingutf-8htmlresponse.text# 二进制数据(图片、PDF等)image_responserequests.get(https://example.com/image.jpg)withopen(image.jpg,wb)asf:f.write(image_response.content)# 大文件流式下载withrequests.get(https://example.com/large_file.zip,streamTrue)asr:r.raise_for_status()withopen(large_file.zip,wb)asf:forchunkinr.iter_content(chunk_size8192):f.write(chunk)print(下载完成)1.3 实战综合运用GET/POST请求下面是一个模拟搜索引擎关键词搜索和翻页爬取的完整示例。importrequestsimporttimeimportrandomfrombs4importBeautifulSoupclassSimpleSpider:def__init__(self):self.sessionrequests.Session()self.session.headers.update({User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36,Accept-Language:zh-CN,zh;q0.9})self.results[]defsearch(self,keyword,max_pages5):print(f开始爬取关键词:{keyword})forpageinrange(1,max_pages1):print(f正在爬取第{page}页...)params{q:keyword,page:page,size:20}responseself._fetch(https://example.com/search,paramsparams)ifnotresponse:print(f第{page}页获取失败,跳过)continueitemsself._parse(response.text)self.results.extend(items)print(f第{page}页提取{len(items)}条数据)# 随机延时,避免过快请求sleep_timerandom.uniform(1.0,2.5)time.sleep(sleep_time)returnself.resultsdef_fetch(self,url,paramsNone):try:responseself.session.get(url,paramsparams,timeout10)response.raise_for_status()returnresponseexceptExceptionase:print(f请求失败:{e})returnNonedef_parse(self,html):soupBeautifulSoup(html,lxml)items[]foriteminsoup.select(div.result-item):items.append({title:item.select_one(h3).text.strip(),url:item.select_one(a)[href],summary:item.select_one(p.summary).text.strip()})returnitemsdefsave(self,filenameresults.json):importjsonwithopen(filename,w,encodingutf-8)asf:json.dump(self.results,f,ensure_asciiFalse,indent2)print(f已保存{len(self.results)}条数据到{filename})# 使用示例spiderSimpleSpider()dataspider.search(Python爬虫教程,max_pages3)spider.save()

相关新闻

C++俄罗斯方块项目实战:从架构设计到性能优化的完整指南

C++俄罗斯方块项目实战:从架构设计到性能优化的完整指南

1. 项目概述:为什么用C重写俄罗斯方块依然值得深究? 俄罗斯方块,这个诞生于上世纪80年代的经典游戏,几乎成了每一位程序员学习图形编程或游戏逻辑的“Hello World”。你可能觉得,用C实现一个俄罗斯方块,听起…

2026/7/30 11:50:41 阅读更多 →
架构揭秘:REFramework如何实现RE引擎游戏的跨平台模组支持

架构揭秘:REFramework如何实现RE引擎游戏的跨平台模组支持

架构揭秘:REFramework如何实现RE引擎游戏的跨平台模组支持 【免费下载链接】REFramework Mod loader, scripting platform, and VR support for all RE Engine games 项目地址: https://gitcode.com/GitHub_Trending/re/REFramework REFramework作为RE Engin…

2026/7/26 18:10:32 阅读更多 →
Linux 下 cat 和 more 的用法

Linux 下 cat 和 more 的用法

Linux 下 cat 和 more 的用法 cat: 一次性显示整个文件 文件过长时会一屏刷到底 # 显示文件内容 cat file.txt# 带行号显示 cat -n file.txt# 连接多个文件 cat file1.txt file2.txt# 将内容重定向写入文件 cat file1.txt file2.txt > combined.txtmore :分页显示&#xff0…

2026/7/26 18:10:32 阅读更多 →

最新新闻

接单做训练反馈APP,我算了三笔账

接单做训练反馈APP,我算了三笔账

这单适不适合用 AI 生成 APP,我用三笔账判断:原型账、返工账、上线账。算完以后,我没有全手写,也没把交付完全交给生成工具,而是把可重复的页面先跑出来,复杂数据留给自己收口。 客户是一个只有 4 名教练的…

2026/7/30 16:25:06 阅读更多 →
项目延期丢订单?全星APQP系统让汽车电子研发周期缩短23%,里程碑自动预警,决策层实时掌控全局。

项目延期丢订单?全星APQP系统让汽车电子研发周期缩短23%,里程碑自动预警,决策层实时掌控全局。

项目延期丢订单?全星APQP系统让汽车电子研发周期缩短23%,里程碑自动预警,决策层实时掌控全局。为什么众多制造企业选择了全星 APQP?在汽车及高端制造业,新产品研发质量直接决定市场胜负。手工台账、分散表格、跨部门协…

2026/7/30 16:25:06 阅读更多 →
Windows 11任务栏自定义工具ExplorerPatcher深度解析:系统稳定性优化与冲突解决方案

Windows 11任务栏自定义工具ExplorerPatcher深度解析:系统稳定性优化与冲突解决方案

Windows 11任务栏自定义工具ExplorerPatcher深度解析:系统稳定性优化与冲突解决方案 【免费下载链接】ExplorerPatcher This project aims to enhance the working environment on Windows 项目地址: https://gitcode.com/GitHub_Trending/ex/ExplorerPatcher …

2026/7/30 16:25:06 阅读更多 →
计算机毕业设计之安卓的校园信息服务APP

计算机毕业设计之安卓的校园信息服务APP

随着互联网的趋势的到来,各行各业都在考虑利用互联网将自己的信息推广出去,最好方式就是建立自己的平台信息,并对其进行管理,随着现在智能手机的普及,人们对于智能手机里面的应用安卓校园信息服务APP也在不断的使用&am…

2026/7/30 16:25:06 阅读更多 →
计算机毕业设计之安卓的教师在线辅导系统

计算机毕业设计之安卓的教师在线辅导系统

随着经济的发展,互联网络时代也在飞速进步,每个行业都在努力发展现在先进技术,通过这些先进的技术来提高自己的水平和优势。本文将讲述设计开发一个安卓的教师在线辅导系统,这个安卓的教师在线辅导系统包括三个部分:学…

2026/7/30 16:25:06 阅读更多 →
QuickRecorder:7大录制模式,重新定义macOS屏幕录制的专业体验

QuickRecorder:7大录制模式,重新定义macOS屏幕录制的专业体验

QuickRecorder:7大录制模式,重新定义macOS屏幕录制的专业体验 【免费下载链接】QuickRecorder A lightweight screen recorder based on ScreenCapture Kit for macOS / 基于 ScreenCapture Kit 的轻量化多功能 macOS 录屏工具 项目地址: https://gitc…

2026/7/30 16:24:06 阅读更多 →

日新闻

Windows驱动存储终极清理工具:DriverStoreExplorer完全指南

Windows驱动存储终极清理工具:DriverStoreExplorer完全指南

Windows驱动存储终极清理工具:DriverStoreExplorer完全指南 【免费下载链接】DriverStoreExplorer Driver Store Explorer 项目地址: https://gitcode.com/gh_mirrors/dr/DriverStoreExplorer 您是否曾因Windows系统盘空间不足而烦恼?是否遇到过设…

2026/7/30 0:00:13 阅读更多 →
如何3步掌握Video Download Helper:网页视频下载的完整实战指南

如何3步掌握Video Download Helper:网页视频下载的完整实战指南

如何3步掌握Video Download Helper:网页视频下载的完整实战指南 【免费下载链接】VideoDownloadHelper Chrome Extension to Help Download Video for Some Video Sites. 项目地址: https://gitcode.com/gh_mirrors/vi/VideoDownloadHelper 你是否曾经在浏览…

2026/7/30 0:00:13 阅读更多 →
“双减”后首个AI备课压力测试报告:覆盖32所中小学的176节AI辅助课,暴露4大隐性增负节点

“双减”后首个AI备课压力测试报告:覆盖32所中小学的176节AI辅助课,暴露4大隐性增负节点

更多请点击: https://intelliparadigm.com 第一章:AI 教师备课辅助 AI 教师备课辅助系统正逐步成为教育数字化转型的核心支撑工具,它并非替代教师,而是通过语义理解、知识图谱与多模态生成能力,将教师从重复性劳动中解…

2026/7/30 0:00:13 阅读更多 →

周新闻

深度学习道路桥梁裂缝检测系统 道路桥梁裂缝检测数据集 道路桥梁病害识别检测数据集

深度学习道路桥梁裂缝检测系统 道路桥梁裂缝检测数据集 道路桥梁病害识别检测数据集

深度学习道路桥梁裂缝检测系统 数据集6000张 完整源码已标注数据集训练好的模型环境配置教程程序运行说明文档,可以直接使用!系统支持图片、视频、摄像头等多种方式检测裂缝,功能强大实用。 1数据集6000张 8各类别

2026/7/29 22:18:20 阅读更多 →
深度学习YOLO模型如何训练 PUBG 绝地求生目标检测数据集

深度学习YOLO模型如何训练 PUBG 绝地求生目标检测数据集

pubg数据集 精选原图1.42万数据 1.49万标签 无任何重复、算法增强或冗余图像! pubg绝地求生目标检测数据集 1分类:e_body,14905个标签,txt格式 共计14244张图,99%为640*640尺寸图像 适合yolo目标检测、AI训练关键词&am…

2026/7/29 14:34:28 阅读更多 →
Apex英雄目标检测数据集 深度学习框架YOLO如何训练APEX数据集

Apex英雄目标检测数据集 深度学习框架YOLO如何训练APEX数据集

Apex检测数据集数据集详情检测类别: allies enemy tag图片总量:7247张训练集:5139张验证集:1425张测试集:683张标注状态:全部已标注,即拿即用数据格式:支持YOLO格式及其他格式&#…

2026/7/29 15:00:03 阅读更多 →

月新闻