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/11/22 1:26:44 阅读更多 →
架构揭秘: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/11/10 15:42:10 阅读更多 →
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/11/20 21:43:22 阅读更多 →

最新新闻

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

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

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

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

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

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

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

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

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

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

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

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

2026/11/21 23:27:35 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

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

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

2026/11/21 23:27:36 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

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

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

2026/11/21 23:27:37 阅读更多 →

日新闻

周新闻

月新闻