urllib(补充)
urllib提供了一系列用于操作URL的功能。
GET
urllib的request模块可以非常方便地抓取URL内容,也就是发送一个GET请求到指定的页面,然后返回HTTP的响应:
例如,对豆瓣的一个URL
https://api.douban.com/v2/book/2129650
进行抓取,并返回响应(这里由于上边的URL打不开,所以更换了一个URL):
from urllib import request with request.urlopen('https://yesno.wtf/api') as f: data=f.read() print('Status:',f.status,f.reason) for k,v in f.getheaders(): print('%s:%s'%(k,v)) print('Data:',data.decode('utf-8'))
可以看到HTTP响应的头和JSON数据:
Status: 200 OK Content-Type:application/json; charset=utf-8 Transfer-Encoding:chunked Connection:close Cache-Control:max-age=0, private, must-revalidate X-Request-Id:53f95db9-473a-48d8-a8d6-9cab6156abe2 X-Runtime:0.001832 X-Content-Type-Options:nosniff Date:Sun, 11 Oct 2020 07:02:02 GMT Server:nginx/1.17.3 + Phusion Passenger 6.0.4 Data: {"answer":"no","forced":false,"image":"https://yesno.wtf/assets/no/20-56c4b19517aa69c8f7081939198341a4.gif"}
如果我们想要模拟浏览器发送GET请求,就需要使用Request对象,通过Request对象添加HTTP头,我们就可以把请求伪装成浏览器。
例如,模拟iPhone 6去请求豆瓣首页:
from urlib import request req=request.Request('https://www.douban.com/') req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25') with request.urlopen(req) as f: print('Status:',f.status,f.reason) for k,v in f.getheaders(): print('%s:%s'%(k,v)) print('Data:',f.read().decode('utf-8')) #由于从网页中读到的数据是UTF-8编码后的,所以要先解码decode('utf-8')
这样豆瓣会返回适合iPhone的移动版网页:
... <meta name="viewport" content="width=device-width, height=device-height, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0"> <meta name="format-detection" content="telephone=no">
<link rel="apple-touch-icon-precomposed" href="https://img3.doubanio.com/f/talion/997f2018d82979da970030a5eb84c77f0123ae5f/pics/icon/m_logo_76.png"> ...
POST
如果要以POST发送一个请求,只需要把参数data以bytes形式传入。
我们模拟一个微博登录,先读取登录的邮箱和口令,然后按照weibo.cn的登录页的格式以username=xxx&password=xxx的编码传入
#Post #模拟微博登录 from urllib import request,parse print('Login to weibo.cn') email = input('Email:') passwd= input('Password:') login_data = parse.urlencode([ ('username',email), ('password',passwd), ('entry','mweibo'), ('client_id',''), ('savestate','1'), ('ec',''), ('pagerefer','https://passport.weibo.cn/signin/welcome?entry=weibo&r=http%3A%2F%2Fm.weibo.cn%2F') ]) req=request.Request('https://passport.weibo.cn/sso/login') req.add_header('Origin','https://passport.weibo.cn') req.add_header('User-Agent',Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25') req.add_header('Referer','https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F') with request.urlopen(req,data=login_data.encode('')) as f: print('Status:',f.status,f.reason) for k,v in f.getheader(): print('%s:%s'%(k,v)) print('Data:',f.read().decode('utf-8'))
Handler
如果还需要更加复杂的控制,比如通过一个Proxy去访问网站,我们需要利用ProxyHandle来处理,示例代码如下:
#Handler from urllib import request proxy_handler= request.ProxyHandler({'http':'http://www.example.com/login.html/'}) proxy_auth_handler=request.ProxyBasicAuthHandler() proxy_auth_handler.add_password('realm','host','username','password') opener=request.build_opener(proxy_handler,proxy_auth_handler) with opener.open('http://www.example.com/login.html') as f: pass
urlib提供的功能就是利用程序去执行各种HTTP请求。如果要模拟浏览器完成特定功能,需要把请求伪装成浏览器。方法是,先监控浏览器发出的请求,再根据浏览器的请求头来伪装,User-Agent头就是用来标识浏览器的。
分类:
爬虫
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性