【python】详解urllib库的操作,requests,error,parse模块

1 篇文章 0 订阅

urllib 是python内置的http请求库,内置的主要是以下几个模块:

  • urllib.request :请求模块
  • urllib.error :异常处理模块
  • urllib.parse :url解析模块
  • urllib.robotparer :robot.txt解析模块

1、urllib实现get或者post请求

urllib.request.urlopen(url,data = None,[timeout,],cafile = None,capath = None,cadefualt = False,context = None)

  • urllib.requests.urlopen --get实例如下:
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
# response得到的是网页的内容,bytes类型的数据,需要用utf-8转为字符串格式
print(response.read().decode('utf-8'))
  • 使用post请求需要传入data,urllib.requests.urlopen --post实例如下:
import urllib.parse
import urllib.request
# 传入的data参数需要bytes类型
data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())

所以,对于get和post请求的方式,只需要传入data就可以进行区分。

  • timeout 参数
import urllib.request
import urllib.parse
import urllib.error
import socket

#url = 'https://python.org/'
url = 'http://httbin.org/get'
data = bytes(urllib.parse.urlencode({'hello':'world'}),encoding = 'utf8')
try:
    
    res = urllib.request.urlopen(url,timeout = 0.1)
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print('TIMEOUT')
# 最终会因为timeout而执行print('TIMEOUT')

2、urllib.requests.Request方法

前文直接用URLopen请求网页,但是不方便添加header之类的信息,因此需要Request来构建。

Request:urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
  • url:必选参数,传入需要请求的链接
  • data:如果要传,必选是bytes(字节流)的类型。如果是参数字典,需要parse解析的urlencode编码为字符串
  • headers:请求头;可以直接添加到Request实例中,或者通过add_headers的方式添加;添加请求头最常用的方法就是通过修改User_Agent来伪装浏览器,python默认的是python-urllib,我们可以通过修改它来伪装浏览器,比如伪装Google浏览器,设置为"User-Agent",“Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36”
  • origin_req_host:请求方的host名称或者IP地址
  • unverifiable:表示这个请求是否无法验证,默认是False,意思是请求权限不够。
  • method:用来指示请求的方法,比如GET、POST、PUT

通过Request构建的请求对象传入urllib.request.urlopen( )打开,如下:

import urllib.request
import urllib.parse
import urllib.error
import socket

#url = 'https://python.org/'
url = 'http://httbin.org/post'

data = bytes(urllib.parse.urlencode({'hello':'world'}),encoding = 'utf8')

headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}

req = urllib.request.Request(url,headers = headers,data = data,method = 'POST')
try:    
    res = urllib.request.urlopen(req,timeout = 1)
    print(res.read().decode('utf-8'))
    print('OJBK')
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print('TIMEOUT')

输出结果是:OJBK
2.1、Handler:更加复杂的方法

首先是urllib.request的BaseHandler类,他是所有其他handler的父类,提供最基本的方法,如default_open( )、protocol_request( )等。

其次,各种常用的子类继承这个BaseHandler类:

  • HTTPHandler() 通过HTTP打开URL
  • CacheFTPHandler() 具有持久FTP连接的FTP处理程序
  • FileHandler() 打开本地文件
  • FTPHandler() 通过FTP打开URL
  • HTTPBasicAuthHandler() 通过HTTP验证处理
  • HTTPCookieProcessor() 处理HTTP cookie
  • HTTPDefaultErrorHandler() 通过引发HTTPError异常处理HTTP错误
  • HTTPDigestAuthHandler() HTTP摘要验证处理
  • HTTPRedirectHandler() 处理HTTP重定向
  • HTTPSHandler() 通过安全HTTP重定向
  • ProxyHandler() 通过代理重定向请求
  • ProxyBasicAuthHandler 基本的代理验证
  • ProxyDigestAuthHandler 摘要代理验证
  • UnknownHandler 处理所有未知URL的处理程序

另一个比较实用的类就是OpenerDirector,可以称之为Opener,我们可以利用handler来构建Opener。

  • ProxyHandler
import urllib.request
from urllib.request import build_opener
proxy_handler = urllib.request.ProxyHandler({
    'http':'http://127.0.0.1:9743',
    'https':'https://127.0.0.1.9743'
})
opener = build_opener(proxy_handler)
response = opener.open('http://www.baidu.com')
print(response.read())

在这里用代理会出错:<urlopen error [WinError 10061] 由于目标计算机积极拒绝,无法连接。>。
一般的代理没什么卵用,代理的研究还有待深入研究,目前较方便的处理的方法是去掉代理即可。

  • HTTPBasicAuthHandler:
import urllib.request
import urllib.parse
import urllib.error
import socket
from urllib.request import HTTPPasswordMgrWithDefaultRealm,HTTPBasicAuthHandler,build_opener

username = 'username'
password = 'password'

#url = 'https://python.org/'
url = 'http://localhost:5000'

p = HTTPPasswordMgrWithDefaultRealm()
p.add_password(None,url,username,password)
auth_handler = HTTPBasicAuthHandler(p)
opener = build_opener(auth_handler)
  • cookies:

首先声明一个Cookiejar对象,,接下来就用HTTPCookieProcessor来构建一个Handler,最后利用build_opener方法构建出Opener,执行open( )函数就可以。

import http.cookiejar, urllib.request
filename = "cookie.txt"
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=A2894B5224134AF4A6C1E1DD34FD2DAE:FG=1
BIDUPSID=A2894B5224134AF4A6C1E1DD34FD2DAE
H_PS_PSSID=1459_25810_21095_26350_27245
PSTM=1538480633
delPer=0
BDSVRTM=0
BD_HOME=0

如果是需要保存cookie到本地文件,需要将CookieJar 换成MozillaCookieJar或者LWPCookieJar,这两者仅是保存的文件类型略有差异。

import urllib.request
import urllib.parse
import urllib.error
import socket
import http.cookiejar, urllib.request
filename = "cookie.txt"

# 保存cooki为文本
# 保存类型有很多种
## 类型1
cookie = http.cookiejar.MozillaCookieJar(filename)
### 类型2
#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)
# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This is a generated file!  Do not edit.

.baidu.com	TRUE	/	FALSE	3685964435	BAIDUID	4708EE5A13C2728EFED018DB3ACE432B:FG=1
.baidu.com	TRUE	/	FALSE	3685964435	BIDUPSID	4708EE5A13C2728EFED018DB3ACE432B
.baidu.com	TRUE	/	FALSE		H_PS_PSSID	1450_21112_26350_27245_20927
.baidu.com	TRUE	/	FALSE	3685964435	PSTM	1538480809
.baidu.com	TRUE	/	FALSE		delPer	0
www.baidu.com	FALSE	/	FALSE		BDSVRTM	0
www.baidu.com	FALSE	/	FALSE		BD_HOME	0

如何读取,调用load()方法来读取本地的Cookie文件,注意的是之前使用的MozillaCookieJar的方法储存的,后期需要声明同样的MozillaCookieJar的方法才能Load。然后通过调用handler的方法和opener的方法完成网页请求。

# 使用相应的方法读取
import http.cookiejar, urllib.request
cookie = http.cookiejar.MozillaCookieJar()
cookie.load('cookie.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')0

3、处理异常

urllib的error模块定义了由urllib.request请求产生的异常。如果请求失败,urllib.request便会抛出error模块的异常。

  • URLError
    URLError类来自urllib的error模块,是继承OSError模块,是异常模块的基类,具有属性reason,即返回错误原因。
from urllib import request,error

try:
    res = request.urlopen('https://cuiiqngcai.com/index.html')
except error.URLError as e:
    print(e.reason)
    
[Errno 11001] getaddrinfo failed
  • HTTPError
    它是URLError的子类,专门用来处理HTTP请求错误,具备三个属性:

1、code:返回HTTP状态码
2、reason:异常原因
3、headers:请求头

try:
    res = request.urlopen('https://cuiqingcai.com/index.html')
except error.HTTPError as e:
    print(e.reason,e.code,e.headers)
    
Not Found 
404 
Server: nginx/1.10.3 (Ubuntu)
Date: Tue, 02 Oct 2018 12:09:55 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: close
Vary: Cookie
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Link: <https://cuiqingcai.com/wp-json/>; rel="https://api.w.org/"

将URLError和HTTPError结合才进行异常处理,首先通过子类HTTPERror来捕获它的错误状态码、原因、headers等信息。如果不是HTTPError,然后捕获URLError,输出错误原因,最后是else来处理正常的逻辑。

import urllib.parse
from urllib import request,error
import socket


try:
    res = request.urlopen('https://cuiqingcai.com/index.html',timeout = 0.1)
except error.HTTPError as e:
    print(e.reason,e.code,e.headers)
except error.URLError as e:
    print(e.reason)
    if isinstance(e.reason,socket.timeout):
        print('TIMEOUT')
else:
    print('ok')

4、解析链接

urllib库里还有parse模块,定义了处理URL的标准接口,例如实现URL各部分的抽取、合并以及链接转换。

  • urlparse:实现URL的识别和分段
from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')

print(type(result),result)
<class 'urllib.parse.ParseResult'> ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')

解析的时候有特定的分隔符,?/ 前面就是scheme,代表协议;第一个 / 符号前面就是netloc,即域名;
后面是path,即访问路径;分号;前面是params,代表参数;问号?后面是查询条件query,一般作为GET类型的URL,#后面是锚点,用于直接定位页面内部的下拉位置。

所以可以得出一个标准的链接格式:

scheme://netloc/path;params?query#fragment

一般的标准URL都会符合上述规则,利用urlparse方法将它分拆开来。除了这种最基本的解析方式之外,就是通过API用法:

--	urlstring,必填项;即待解析的URL
--	scheme:默认(https,http)协议。假如这个链接没有带协议信息,会将传入的scheme作为默认的协议;
res = urlparse('http://www.baidu.com/index.html;user?id=5#comment',scheme='https')
res
Out[36]: ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')
# 如果url含有scheme信息,则会返回url里面的值,而不是参数scheme传进去的值

res = urlparse('www.baidu.com/index.html;user?id=5#comment',scheme='https')
res
Out[38]: ParseResult(scheme='https', netloc='', path='www.baidu.com/index.html', params='user', query='id=5', fragment='comment')
#可以发现,如果URL没有包含scheme信息,那么我们传进去的值就会被使用,同时域名会加载path里;
--	allow_fragements:锚点;如果设置为False,fragment就会被忽略,它会被解析为path、parameters或者query的一部分。
  • urlunparse

合成url的函数,必须传入6个参数,可以是元组或者是参数列表的形式:

data = ['https','www.baidu.com','/index.html','user','id=5','comment']
from urllib.parse import urlunparse

urlunparse(data)
Out[41]: 'https://www.baidu.com/index.html;user?id=5#comment'
  • urlsplit

这个方法和urlparse很像,只返回5个值,它不再单独解析出params,会将params合并到path中去:

urlsplit('http://www.baidu.com/index.html;user?id=5#comment')
Out[43]: SplitResult(scheme='http', netloc='www.baidu.com', path='/index.html;user', query='id=5', fragment='comment')

可以通过属性或者索引来获取值:
res = urlsplit('http://www.baidu.com/index.html;user?id=5#comment')
res.path
Out[46]: '/index.html;user'
res[1]
Out[47]: 'www.baidu.com'
  • urlunsplit

与urlunparse相似,传入的参数也是一个列表或者元组这类可迭代对象,唯一的区别也是长度,必须是传入5个参数

data = ['https','www.baidu.com','/index.html?user','id=5','comment']
from urllib.parse import urlunsplit

urlunsplit(data)
Out[50]: 'https://www.baidu.com/index.html?user?id=5#comment'
  • urljoin
    对于urlunsplit和urlunparse方法,可以完成链接的合并,不过必须长度是特定的,链接的每一部分都要清晰分开。通过urljoin,可以提供一个base_url作为第一个参数,新的链接作为第二个参数,该方法会分析base_url 的scheme、netloc和path这三个内容对新链接缺失的部分进行补充。
from urllib.parse import urljoin

print(urljoin('http://www.baidu.com','FAQ.html'))
http://www.baidu.com/FAQ.html

print(urljoin('http://www.baidu.com','https://cuiqingcai.com/FAQ.html'))
https://cuiqingcai.com/FAQ.html      #如果scheme、netloc、path在新的链接存在,就使用新的链接内容

print(urljoin('http://www.baidu.com/about.html','https://cuiqingcai.com/FAQ.html'))
https://cuiqingcai.com/FAQ.html     #base_url的params、query、fragment是不起作用

print(urljoin('http://www.baidu.com/about.html','https://cuiqingcai.com/FAQ.html?question=2'))
https://cuiqingcai.com/FAQ.html?question=2

print(urljoin('http://www.baidu.com/about.html','?category=2#comment'))
http://www.baidu.com/about.html?category=2#comment   #如果上述三项在新的链接里不存在,就予以补充

print(urljoin('www.baidu.com/about.html','?category=2#comment'))
www.baidu.com/about.html?category=2#comment

#可以得出如果base_url提供了三项内容scheme、netloc、path。如果上述三项在新的链接里不存在,就予以补充。如果在新的链接存在,就使用新的链接内容。而base_url的params、query、fragment是不起作用。
  • urlencode

对于构造GET请求参数时非常有用,首先声明一个字典将参数表示出来,然后调用urlencode的方法将其序列化为GET请求参数。

from urllib.parse import urlencode

params = {'name':'bruce','age':20}
base_url = 'http://baidu.com?'
base_url + urlencode(params) 
Out[67]: 'http://baidu.com?name=bruce&age=20'
  • parse_qs

反序列化,将GET请求的参数解析出来

parse_qs('name=bruce&age=20')
Out[72]: {'age': ['20'], 'name': ['bruce']}
  • parse_qsl

将参数转化为元组组成的列表

from urllib.parse import parse_qsl

parse_qsl('name=bruce&age=20')
Out[74]: [('name', 'bruce'), ('age', '20')]
  • quote

该方法将内容转化为URL编码格式,此方法可以将中文字符串转化为URL编码

from urllib.parse import quote

keyword = '大锤'

url = 'http://www.baidu.com?s?wd =' +quote(keyword)

url
Out[78]: 'http://www.baidu.com?s?wd =%E5%A4%A7%E9%94%A4'
  • unquote
    利用unquote进行还原
from urllib.parse import unquote

unquote(url)
Out[80]: 'http://www.baidu.com?s?wd =大锤'
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值