在Python 2中,有urllib和urllib2两个库来实现请求的发送。而在Python 3中,已经不存在urllib2这个库了,统一为urllib,其官方文档连接为:https://docs.python.org/3/library/urllib.html。php
urllib库,是Python内置的HTTP请求库,也就是说不须要额外安装便可使用。它包含以下4个模块:html
这里重点讲解一下前3个模块。python
使用urllib的request模块,咱们能够方便地实现请求的发送并获得响应。nginx
打开指定的URLjson
(1)语法浏览器
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
(2)示例服务器
基本使用cookie
import urllib.request response = urllib.request.urlopen('https://www.python.org') print(response.read().decode('utf-8'))
传递数据网络
import urllib.parse import urllib.request data = bytes(urllib.parse.urlencode({'name': 'helloworld'}), encoding='utf8') # 须要将数据转换成bytes对象 response = urllib.request.urlopen('http://httpbin.org/post', data=data) print(response.read())
设置超时时间session
import socket import urllib.request import urllib.error try: response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1) # 设置0.1秒请求就会超时 except urllib.error.URLError as e: if isinstance(e.reason, socket.timeout): print('TIMEOUT')
(3)urllib.request.urlopen()响应结果操做
首先,利用type()方法输出响应的类型:
import urllib.request response = urllib.request.urlopen('https://www.python.org') print(type(response)) 输出结果: <class 'http.client.HTTPResponse'>
能够发现,它是一个HTTPResposne
类型的对象。它主要包含read()
、readinto()
、getheader(name)
、getheaders()
、fileno()
等方法,以及msg
、version
、status
、reason
、debuglevel
、closed
等属性。
import urllib.request response = urllib.request.urlopen('https://www.python.org') print(response.status) print(response.getheaders()) print(response.getheader('Server')) 输出结果: 200 [('Server', 'nginx'), ('Content-Type', 'text/html; charset=utf-8'), ('X-Frame-Options', 'SAMEORIGIN'), ('x-xss-protection', '1; mode=block'), ('X-Clacks-Overhead', 'GNU Terry Pratchett'), ('Via', '1.1 varnish'), ('Content-Length', '49094'), ('Accept-Ranges', 'bytes'), ('Date', 'Sun, 30 Sep 2018 03:03:43 GMT'), ('Via', '1.1 varnish'), ('Age', '1389'), ('Connection', 'close'), ('X-Served-By', 'cache-iad2124-IAD, cache-hnd18721-HND'), ('X-Cache', 'HIT, HIT'), ('X-Cache-Hits', '3, 881'), ('X-Timer', 'S1538276623.322806,VS0,VE0'), ('Vary', 'Cookie'), ('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')] nginx
URL请求的抽象类,咱们知道利用urlopen()
方法能够实现最基本请求的发起,但这几个简单的参数并不足以构建一个完整的请求。若是请求中须要加入Headers等信息,就能够利用更强大的Request
类来构建。
(1)构造方法
class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
bytes
(字节流)类型的。若是它是字典,能够先用urllib.parse
模块里的urlencode()
编码。跟urlopen()方法的data参数同样。headers
参数直接构造,也能够经过调用请求实例的add_header()
方法添加。False
,意思就是说用户没有足够权限来选择接收这个请求的结果。例如,咱们请求一个HTML文档中的图片,可是咱们没有自动抓取图像的权限,这时unverifiable的值就是
True。(2)示例
from urllib import request, parse
url = 'http://httpbin.org/post' headers = { 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' } dict = { 'name': 'Germey' } data = bytes(parse.urlencode(dict), encoding='utf8') req = request.Request(url=url, data=data, headers=headers, method='POST') req.add_header('Host', 'httpbin.org') response = request.urlopen(req) print(response.read().decode('utf-8')) 输出结果: { "args": {}, "data": "", "files": {}, "form": { "name": "Germey" }, "headers": { "Accept-Encoding": "identity", "Connection": "close", "Content-Length": "11", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)" }, "json": null, "origin": "123.147.199.132", "url": "http://httpbin.org/post" }
除了上面提到的简单的构造请求,有点时候还会遇到一些更高级的东西,好比,登陆验证、Cookie、代理等一些处理。就须要一个更强大的工具来作这些处理,urllib.request
模块里的BaseHandler
类这个时候就派上了用场了,它是全部其余Handler
的父类,它提供了最基本的方法,例如default_open()
、protocol_request()
等。
下面是一些继承BaseHandler
类的子类:
HTTPDefaultErrorHandler
:用于处理HTTP响应错误,错误都会抛出HTTPError
类型的异常。HTTPRedirectHandler
:用于处理重定向。HTTPCookieProcessor
:用于处理Cookies。ProxyHandler
:用于设置代理,默认代理为空。HTTPPasswordMgr
:用于管理密码,它维护了用户名和密码的表。HTTPBasicAuthHandler
:用于管理认证,若是一个连接打开时须要认证,那么能够用它来解决认证问题。另外,还有其余的Handler
类请参考官方文档:https://docs.python.org/3/library/urllib.request.html#urllib.request.BaseHandler。
示例:
(1)登陆验证
有些网站在打开时就会弹出提示框,直接提示你输入用户名和密码,验证成功后才能查看页面,以下图所示:
from urllib.request import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, build_opener from urllib.error import URLError username = 'username' password = 'password' url = 'http://localhost:5000/' p = HTTPPasswordMgrWithDefaultRealm() p.add_password(None, url, username, password) auth_handler = HTTPBasicAuthHandler(p) opener = build_opener(auth_handler) try: result = opener.open(url) html = result.read().decode('utf-8') print(html) except URLError as e: print(e.reason)
代码解释:
首先实例化HTTPBasicAuthHandler
对象,其参数是HTTPPasswordMgrWithDefaultRealm
对象,它利用add_password()
添加进去用户名和密码,这样就创建了一个处理验证的Handler
。
接下来,利用这个Handler
并使用build_opener()
方法构建一个Opener
,这个Opener
在发送请求时就至关于已经验证成功了。
接下来,利用Opener
的open()
方法打开连接,就能够完成验证了。这里获取到的结果就是验证后的页面源码内容。
(2)代理
在作爬虫的时候,免不了要使用代理,若是要添加代理,能够这样作:
from urllib.error import URLError from urllib.request import ProxyHandler, build_opener proxy_handler = ProxyHandler({ 'http': 'http://127.0.0.1:9743', 'https': 'https://127.0.0.1:9743' }) opener = build_opener(proxy_handler) try: response = opener.open('https://www.baidu.com') print(response.read().decode('utf-8')) except URLError as e: print(e.reason)
代码解释:
这里咱们在本地搭建了一个代理,它运行在9743端口上。
这里使用了ProxyHandler
,其参数是一个字典,键名是协议类型(好比HTTP或者HTTPS等),键值是代理连接,能够添加多个代理。
而后,利用这个Handler及build_opener()
方法构造一个Opener
,以后发送请求便可。
(3)Cookie
a.获取网站的Cookie
import http.cookiejar, urllib.request cookie = http.cookiejar.CookieJar() handler = urllib.request.HTTPCookieProcessor(cookie) opener = urllib.request.build_opener(handler) response = opener.open('http://www.baidu.com') for item in cookie: print(item.name+"="+item.value) 输出结果: BAIDUID=ABC21AF733113C91DA9A89E3E7CD9C53:FG=1 BIDUPSID=ABC21AF733113C91DA9A89E3E7CD9C53 H_PS_PSSID=1444_21087 PSTM=1538278865 delPer=0 BDSVRTM=0 BD_HOME=0
代码解释:
首先,咱们必须声明一个CookieJar
对象。
接下来,就须要利用HTTPCookieProcessor
来构建一个Handler。
最后利用build_opener()
方法构建出Opener
,执行open()
函数便可。
b.将cookie保存成Mozilla型浏览器格式的Cookies文件
import http.cookiejar, urllib.request filename = 'cookies.txt' cookie = http.cookiejar.MozillaCookieJar(filename) handler = urllib.request.HTTPCookieProcessor(cookie) opener = urllib.request.build_opener(handler) response = opener.open('http://www.baidu.com') cookie.save(ignore_discard=True, ignore_expires=True)
此时,须要将CookieJar
换成MozillaCookieJar,
执行上面的程序会生成了一个cookies.txt文件。
c.读取Mozilla行浏览器格式的Cookie文件
import http.cookiejar, urllib.request cookie = http.cookiejar.MozillaCookieJar() cookie.load('cookies.txt', ignore_discard=True, ignore_expires=True) handler = urllib.request.HTTPCookieProcessor(cookie) opener = urllib.request.build_opener(handler) response = opener.open('http://www.baidu.com') print(response.read().decode('utf-8'))
运行结果正常的话,会输出百度网页的源代码。
d.将Cookie文件保存成libwww-perl(LWP)格式的Cookies文件
import http.cookiejar, urllib.request filename = 'cookies.txt' cookie = http.cookiejar.LWPCookieJar(filename) handler = urllib.request.HTTPCookieProcessor(cookie) opener = urllib.request.build_opener(handler) response = opener.open('http://www.baidu.com') cookie.save(ignore_discard=True, ignore_expires=True)
此时,须要将MozillaCookieJar换成LWPCookieJar,
执行上面的程序会生成了一个cookies.txt文件。
e.读取libwww-perl(LWP)格式的Cookies文件
import http.cookiejar, urllib.request cookie = http.cookiejar.LWPCookieJar() cookie.load('cookies.txt', ignore_discard=True, ignore_expires=True) handler = urllib.request.HTTPCookieProcessor(cookie) opener = urllib.request.build_opener(handler) response = opener.open('http://www.baidu.com') print(response.read().decode('utf-8'))
运行结果正常的话,会输出百度网页的源代码。
urllib的error
模块定义了由request
模块产生的异常。若是出现了问题,request
模块便会抛出error
模块中定义的异常。
URLError类来自urllib库的error模块,它继承自OSError类,是error异常模块的基类,由request模块生的异常均可以经过捕获这个类来处理。它具备一个属性reason,即返回错误的缘由。
from urllib import request, error try: response = request.urlopen('https://blog.csdn.net/1') except error.URLError as e: print(e.reason) 输出结果: Not Found
它是URLError
的子类,专门用来处理HTTP请求错误,好比认证请求失败等。它有以下3个属性。
code
:返回HTTP状态码,好比404表示网页不存在,500表示服务器内部错误等。reason
:同父类同样,用于返回错误的缘由。headers
:返回请求头。from urllib import request,error try: response = request.urlopen('https://blog.csdn.net/1') except error.HTTPError as e: print(e.reason, e.code, e.headers, sep='\n') 输出结果: Not Found 404 Server: openresty Date: Sun, 30 Sep 2018 06:13:52 GMT Content-Type: text/html; charset=utf-8 Content-Length: 12868 Connection: close Vary: Accept-Encoding
由于URLError
是HTTPError
的父类,因此能够先选择捕获子类的错误,再去捕获父类的错误,因此上述代码更好的写法以下:
from urllib import request, error
try: response = request.urlopen('https://blog.csdn.net/1') except error.HTTPError as e: print(e.reason, e.code, e.headers, sep='\n') except error.URLError as e: print(e.reason) else: print('Request Successfully') 输出结果: Not Found 404 Server: openresty Date: Sun, 30 Sep 2018 06:17:53 GMT Content-Type: text/html; charset=utf-8 Content-Length: 12868 Connection: close Vary: Accept-Encoding Set-Cookie: uuid_tt_dd=10_20732824360-1538288273861-180630; Expires=Thu, 01 Jan 2025 00:00:00 GMT; Path=/; Domain=.csdn.net; Set-Cookie: dc_session_id=10_1538288273861.705662; Expires=Thu, 01 Jan 2025 00:00:00 GMT; Path=/; Domain=.csdn.net; ETag: "5b0fa58c-3244"
有时候,reason
属性返回的不必定是字符串,也多是一个对象。示例以下:
import socket import urllib.request import urllib.error try: response = urllib.request.urlopen('https://www.baidu.com', timeout=0.01) except urllib.error.URLError as e: print(type(e.reason)) if isinstance(e.reason, socket.timeout): print('TIMEOUT') 输出结果: <class 'socket.timeout'> TIMEOUT
parse模块定义了处理URL的标准接口,例如实现URL各部分的抽取、合并以及连接转换。它支持以下协议的URL处理:file、ftp、gopher、hdl、http、https、imap、mailto、 mms、news、nntp、prospero、rsync、rtsp、rtspu、sftp、 sip、sips、snews、svn、svn+ssh、telnet和wais。
该方法能够实现URL的识别和分段。
(1)语法
urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)
urlstring
:这是必填项,即待解析的URL。scheme
:它是默认的协议(好比http
或https
等)allow_fragments
:便是否忽略fragment
。若是它被设置为False
,fragment
部分就会被忽略,它会被解析为path
、parameters
或者query
的一部分,而fragment
部分为空。一般一个基本的URL由6大组件组成(scheme://netloc/path;parameters?query#fragment
),每一个元素组都为 String 字符串类型,或者为空。例如:http://www.baidu.com/index.html;user?id=5#comment
除这六大组件外,该类具备如下附加的只读便利属性(可看下表):
属性 | 索引 | 值 | 值若是不存在 |
scheme | 0 | URL 协议 | scheme 参数 |
netloc | 1 | 域名及网络端口 | 空字符串 |
path | 2 | 分层路径 | 空字符串 |
params | 3 | 最后一个路径元素参数 | 空字符串 |
query | 4 | Query 组件 | 空字符串 |
fragment | 5 | 片断标志符 | 空字符串 |
username | 用户名 | None | |
password | Password | None | |
hostname | 主机名 (小写) | None | |
port | 若是存在,端口值为整数 | None |
(2)示例
from urllib.parse import urlparse result = urlparse('http://www.baidu.com/index.html;user?id=5#comment') print(type(result), result) print(result.scheme, result[0]) print(result.netloc, result[1]) print(result.path, result[2]) print(result.params, result[3]) print(result.query, result[4]) print(result.fragment, result[5]) 输出结果: <class 'urllib.parse.ParseResult'> ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment') http http www.baidu.com www.baidu.com /index.html /index.html user user id=5 id=5 comment comment
能够看到,返回结果是一个ParseResult
类型的对象,它包含6部分,分别是scheme
、netloc
、path
、params
、query
和fragment
。
有了urlparse()
,相应地就有了它的对立方法urlunparse()
。它接受的参数是一个可迭代对象,可是它的长度必须是6,不然会抛出参数数量不足或者过多的问题。
from urllib.parse import urlunparse data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment'] print(urlunparse(data)) 输出结果: http://www.baidu.com/index.html;user?a=6#comment
该方法能够提供一个base_url
(基础连接)做为第一个参数,将新的连接做为第二个参数,该方法会分析base_url
的scheme
、netloc
和path
这3个内容并对新连接缺失的部分进行补充,最后返回结果。
from urllib.parse import urljoin
print(urljoin('http://www.baidu.com', 'FAQ.html')) print(urljoin('http://www.baidu.com', 'https://cuiqingcai.com/FAQ.html')) print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html')) print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html?question=2')) print(urljoin('http://www.baidu.com?wd=abc', 'https://cuiqingcai.com/index.php')) print(urljoin('http://www.baidu.com', '?category=2#comment')) print(urljoin('www.baidu.com', '?category=2#comment')) print(urljoin('www.baidu.com#comment', '?category=2')) 输出结果: http://www.baidu.com/FAQ.html https://cuiqingcai.com/FAQ.html https://cuiqingcai.com/FAQ.html https://cuiqingcai.com/FAQ.html?question=2 https://cuiqingcai.com/index.php http://www.baidu.com?category=2#comment www.baidu.com?category=2#comment www.baidu.com?category=2
能够发现,base_url
提供了三项内容scheme
、netloc
和path
。若是这3项在新的连接里不存在,就予以补充;若是新的连接存在,就使用新的连接的部分。而base_url
中的params
、query
和fragment
是不起做用的。
该方法能够构造GET请求参数。
from urllib.parse import urlencode
params = { 'name': 'germey', 'age': 22 } base_url = 'http://www.baidu.com?' url = base_url + urlencode(params) print(url) 输出结果: http://www.baidu.com?name=germey&age=22
该方法能够将一串GET请求参数转换成字典。
from urllib.parse import parse_qs
query = 'name=germey&age=22' print(parse_qs(query)) 输出结果: {'name': ['germey'], 'age': ['22']}
该方法能够将一串GET请求参数转换成元组组成的列表。
from urllib.parse import parse_qsl
query = 'name=germey&age=22' print(parse_qsl(query)) 输出结果: [('name', 'germey'), ('age', '22')]
能够看到,运行结果是一个列表,而列表中的每个元素都是一个元组,元组的第一个内容是参数名,第二个内容是参数值。
该方法能够将内容转化为URL编码的格式。RL中带有中文参数时,有时可能会致使乱码的问题,此时用这个方法能够将中文字符转化为URL编码。
from urllib.parse import quote
keyword = '美女' url = 'https://www.baidu.com/s?wd=' + quote(keyword) print(url) 输出结果: https://www.baidu.com/s?wd=%E7%BE%8E%E5%A5%B3
有了quote()
方法,固然还有unquote()
方法,它能够进行URL解码。
from urllib.parse import unquote url = 'https://www.baidu.com/s?wd=%E7%BE%8E%E5%A5%B3' print(unquote(url)) 输出结果: https://www.baidu.com/s?wd=美女
本文参考:静觅的Python3网络爬虫开发实战