Python-urllib模块

模块中的方法 https://www.cnblogs.com/sysu-blackbear/p/3629420.html
Get
urllib的request模块可以非常方便地抓取URL内容,也就是发送一个GET请求到指定的页面,然后返回HTTP的响应:
例如,对豆瓣的一个URLhttps://api.douban.com/v2/book/2129650进行抓取,并返回响应:

#!/usr/bin/python
#-*-coding:UTF-8-*-
 
From urllib importrequest
 
withrequest.urlopen('https://api.douban.com/v2/book/2129650') as f:
data=f.read()
print('status:',f.status,f.reason)
fork,vinf.getheaders():
print('%s:%s'%(k,v))

print(‘data:’,data.decode(‘utf-8’))

可以看到HTTP响应的头和JSON数据:
Status: 200 OK
Server: nginx
Date: Tue, 26 May 2015 10:02:27 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 2049
Connection: close
Expires: Sun, 1 Jan 2006 01:00:00 GMT
Pragma: no-cache
Cache-Control: must-revalidate, no-cache, private
X-DAE-Node: pidl1
Data: {“rating”:{“max”:10,“numRaters”:16,“average”:“7.4”,“min”:0},“subtitle”:"",“author”:[“廖雪峰编著”],“pubdate”:“2007-6”,…}

如果我们要想模拟浏览器发送GET请求,就需要使用Request对象,通过往Request对象添加HTTP头,我们就可以把请求伪装成浏览器。例如,模拟iPhone 6去请求豆瓣首页:

#!/usr/bin/python
#-*-coding:UTF-8-*-
 
fromurllibimportrequest
 
req=request.Request('http://www.douban.com/')
req.add_header('User-Agent','Mozilla/6.0(iPhone;CPUiPhoneOS8_0likeMacOSX)AppleWebKit/536.26(KHTML,likeGecko)Version/8.0Mobile/10A5376eSafari/8536.25')
withrequest.urlopen(req)asf:
print('Status:',f.status,f.reason)
fork,vinf.getheaders():
print('%s:%s'%(k,v))
print('Data:',f.read().decode('utf-8'))
print('data:',data.decode('utf-8'))

这样豆瓣会返回适合iPhone的移动版网页:





Post
如果要以POST发送一个请求,只需要把参数data以bytes形式传入
我们模拟一个微博登录,先读取登录的邮箱和口令,然后按照weibo.cn的登录页的格式以username=xxx&password=xxx的编码传入:

#!/usr/bin/python
#-*-coding:UTF-8-*-
 
fromurllibimportrequest,parse
print('Logintoweibo.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=mweibo&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;CPUiPhoneOS8_0likeMacOSX)AppleWebKit/536.26(KHTML,likeGecko)Version/8.0Mobile/10A5376eSafari/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')
withrequest.urlopen(req,data=login_data.encode('utf-8'))asf:
print('Status:',f.status,f.reason)
fork,vinf.getheaders():
print('%s:%s'%(k,v))
print('Data:',f.read().decode('utf-8'))
-------------------------------------------------

如果登录成功,我们获得的响应如下:
Status: 200 OK
Server: nginx/1.2.0

Set-Cookie: SSOLoginState=1432620126; path=/; domain=weibo.cn

Data: {“retcode”:20000000,“msg”:"",“data”:{…,“uid”:“1658384301”}}
如果登录失败,我们获得的响应如下:

Data: {“retcode”:50011015,“msg”:"\u7528\u6237\u540d\u6216\u5bc6\u7801\u9519\u8bef",“data”:{“username”:“example@python.org”,“errline”:536}}
Handler
如果还需要更复杂的控制,比如通过一个Proxy去访问网站,我们需要利用ProxyHandler来处理,示例代码如下:
proxy_handler = urllib.request.ProxyHandler({‘http’: ‘http://www.example.com:3128/’})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password(‘realm’, ‘host’, ‘username’, ‘password’)
opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
with opener.open(‘http://www.example.com/login.html’) as f:
pass

小结
urllib提供的功能就是利用程序去执行各种HTTP请求。如果要模拟浏览器完成特定功能,需要把请求伪装成浏览器。伪装的方法是先监控浏览器发出的请求,再根据浏览器的请求头来伪装,User-Agent头就是用来标识浏览器的。

来自 https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432688314740a0aed473a39f47b09c8c7274c9ab6aee000/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值