您好,欢迎访问一九零五行业门户网

一篇文章带你搞定Python中urllib库(操作URL)

一、操作urlurllib提供了一系列用于操作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头就是用来标识浏览器的。
以上就是一篇文章带你搞定python中urllib库(操作url)的详细内容。
其它类似信息

推荐信息