一篇文章带你搞定Python中urllib库(操作URL)
回复“Go语言”即可获赠Python从入门到进阶共10本电子书
Hey,大家好呀,我是Go进阶者。
一、操作URL
urllib提供了一系列用于操作URL的功能。分类讲解相关内容。
二、Get()
urllib的request模块可以非常方便地抓取URL内容,也就是发送一个GET请求到指定的页面,然后返回HTTP的响应:
例如,对豆瓣的URLhttps://api.growingio.com/v2/22c937bbd8ebd703f2d8e9445f7dfd03/web/pv?stm=1593747087078进行抓取,并返回响应:

from urllib import requestwith request.urlopen('https://api.growingio.com/v2/22c937bbd8ebd703f2d8e9445f7dfd03/web/pv?stm=1593747087078') 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数据:

如果要想模拟浏览器发送GET请求,就需要使用Request对象,通过往Request对象添加HTTP头,就可以把请求伪装成浏览器。例如,模拟iPhone 6去请求豆瓣首页:
from urllib import requestreq = request.Request('http://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'))
这样豆瓣会返回适合iPhone的移动版网页:

三、Post()

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

from urllib import request, parseprint('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=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')#构造User-Agentreq.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('utf-8')) 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'))
如果登录成功,获得的响应如下:

如果登录失败,获得的响应如下:

四、Handler
如果还需要更复杂的控制,比如通过一个Proxy去访问网站,需要利用ProxyHandler来处理,示例代码如下:
import urllib.request# 构建了两个代理Handler,一个有代理IP,一个没有代理IPhttpproxy_handler = urllib.request.ProxyHandler({"https": "27.191.234.69:9999"})nullproxy_handler = urllib.request.ProxyHandler({})# 定义一个代理开关proxySwitch = True# 通过 urllib.request.build_opener()方法使用这些代理Handler对象,创建自定义opener对象# 根据代理开关是否打开,使用不同的代理模式if proxySwitch:opener = urllib.request.build_opener(httpproxy_handler)else:opener = urllib.request.build_opener(nullproxy_handler)request = urllib.request.Request("http://www.baidu.com/")# 1. 如果这么写,只有使用opener.open()方法发送请求才使用自定义的代理,而urlopen()则不使用自定义代理。response = opener.open(request)# 2. 如果这么写,就是将opener应用到全局,之后所有的,不管是opener.open()还是urlopen() 发送请求,都将使用自定义代理。# urllib.request.install_opener(opener)# response = urllib.request.urlopen(request)# 获取服务器响应内容html = response.read().decode("utf-8")# 打印结果print(html)
如果代理成功返回网址的信息。

如果网址出错或者代理地址有误,返回下面界面。

五、总结
使用Python语言,能够帮助大家更好的学习Python。urllib提供的功能就是利用程序去执行各种HTTP请求。如果要模拟浏览器完成特定功能,需要把请求伪装成浏览器。伪装的方法是先监控浏j览器发出的请求,再根据浏览器的请求头来伪装,User-Agent头就是用来标识浏览器的。
我是Go进阶者,如果觉得还不错,记得动手点赞一下哈。感谢你的观看! 小伙伴们,快快用实践一下吧!如果在学习过程中,有遇到任何问题,欢迎加我好友,我拉你进Python学习交流群共同探讨学习。
------------------- End -------------------
往期精彩文章推荐:

欢迎大家点赞,留言,转发,转载,感谢大家的相伴与支持
想加入Python学习群请在后台回复【入群】
万水千山总是情,点个【在看】行不行
