python模塊(包)之urllib
urllib:官方文檔是最好的模塊表達(dá)說(shuō)明。
urllib is a package that collects several modules for working with URLs:
- urllib.request for opening and reading URLs
- urllib.error containing the exceptions raised by urllib.request
- urllib.parse for parsing URLs
- urllib.robotparser for parsing robots.txt files
大體來(lái)說(shuō)就是urllib是一個(gè)包含request、error、parse、robotparser四個(gè)模塊,關(guān)乎網(wǎng)絡(luò)資源請(qǐng)求的包。request模塊用來(lái)發(fā)起網(wǎng)絡(luò)資源請(qǐng)求;error模塊用來(lái)在request網(wǎng)絡(luò)資源過(guò)程中搜集異常報(bào)錯(cuò);parse模塊用來(lái)對(duì)url地址進(jìn)行處理;robotparser模塊用來(lái)解析robots.txt文件(未知)。
1、request
The urllib.request module defines functions and classes which help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more.
1.1 方法
urllib.request.urlopen(url, data=None, [timeout, ], cafile=None, capath=None, cadefault=False, context=None):
- url,可以是url地址字符串,或者是Request對(duì)象(下面會(huì)提到)。
- data,指定發(fā)送到服務(wù)器的數(shù)據(jù)對(duì)象。
- cafile、capath,發(fā)起HTTPS請(qǐng)求時(shí)指定一組可信的CA證書。cafile應(yīng)指向包含一系列CA證書的單個(gè)文件,而capath應(yīng)指向散列證書文件的目錄。
- context,該參數(shù)若被指定,必須是
ssl.SSLContext
對(duì)象。 - timeout,請(qǐng)求超時(shí)時(shí)間。
這里一般url、data、timeout三個(gè)參數(shù)還比較常用。
該函數(shù)返回一個(gè)上下文管理對(duì)象,包含一下幾種方法獲取返回結(jié)果的相關(guān)信息:
- geturl():返回檢索的資源的URL,通常用于確定是否遵循重定向。
- info():以
email.message_from_string()
實(shí)例的形式返回頁(yè)面的元信息,如頭信息。 - getcode():返回http響應(yīng)的狀態(tài)碼。
對(duì)于http和https,除上述的幾個(gè)函數(shù)獲取信息外,該函數(shù)返回也是對(duì)http.client.HTTPResponse
稍加修改的對(duì)象,其詳細(xì)說(shuō)明見(jiàn)下方官檔。
HTTPResponse Objects
這個(gè)對(duì)象常用方法有:
- read():讀取響應(yīng)主體,數(shù)據(jù)格式為bytes類型,需要decode()解碼,要按編碼轉(zhuǎn)換成str類型。
- msg:http.client.HTTPMessage包含響應(yīng)標(biāo)頭實(shí)例。
- status:服務(wù)器的狀態(tài)碼。
- reason:服務(wù)器返回的原因短語(yǔ)。
- closed:數(shù)據(jù)流被關(guān)閉時(shí)為True。
在查看urllib的源碼request.py
找到類OpenerDirector
,其下面方法open
可以找到下面幾行代碼:
if isinstance(fullurl, str):
req = Request(fullurl, data)
else:
req = fullurl
if data is not None:
req.data = data
urllib.request.urlopen() 方面介紹里面提到:請(qǐng)求資源可以是url地址字符串,或者是Request對(duì)象。再看上面一段代碼isinstance(fullurl, str)傳遞的fullurl是str的實(shí)例對(duì)象,就將fullurl等轉(zhuǎn)化為Request的實(shí)例對(duì)象。
所以請(qǐng)求資源是url地址字符串或是Request對(duì)象都殊途同歸,最終會(huì)轉(zhuǎn)為Request的實(shí)例對(duì)象進(jìn)行資源請(qǐng)求。下面的子類會(huì)對(duì)Request對(duì)象進(jìn)行詳細(xì)介紹。
附加這個(gè)方法對(duì)應(yīng)的去注釋源碼。
def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
*, cafile=None, capath=None, cadefault=False, context=None):
global _opener
if cafile or capath or cadefault:
import warnings
warnings.warn("cafile, cpath and cadefault are deprecated, use a "
"custom context instead.", DeprecationWarning, 2)
if context is not None:
raise ValueError(
"You can't pass both context and any of cafile, capath, and "
"cadefault"
)
if not _have_ssl:
raise ValueError('SSL support not available')
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH,
cafile=cafile,
capath=capath)
https_handler = HTTPSHandler(context=context)
opener = build_opener(https_handler)
elif context:
https_handler = HTTPSHandler(context=context)
opener = build_opener(https_handler)
elif _opener is None:
_opener = opener = build_opener()
else:
opener = _opener
這里面注意幾個(gè)變量。
a、https_handler:姑且稱為資源構(gòu)造器,它相當(dāng)于處理不同網(wǎng)絡(luò)資源的句柄對(duì)象,如HTTPHandler、HTTPSHandler、FileHandler、FTPHandler、UnknownHandler等類的實(shí)例對(duì)象。
b、opener = build_opener(https_handler):姑且稱為資源鑰匙,它是一個(gè)OpenerDirector
類的實(shí)例對(duì)象,其參數(shù)是上面說(shuō)的資源構(gòu)造器,用這把鑰匙可以打開(kāi)網(wǎng)絡(luò)的任意資源。
下面繼續(xù)request
模塊的方法介紹。
urllib.request.build_opener([handler, ...]):構(gòu)造資源鑰匙,它是一個(gè)OpenerDirector
類的實(shí)例對(duì)象,其參數(shù)是上面說(shuō)的資源構(gòu)造器。
- handler,HTTPHandler、HTTPSHandler、FileHandler、FTPHandler、UnknownHandler等類的實(shí)例對(duì)象。
urllib.request.install_opener(opener):插入資源鑰匙,載入OpenerDirector
子類的實(shí)例對(duì)象,用來(lái)請(qǐng)求網(wǎng)絡(luò)資源。
- opener,常為build_opener([handler, ...])方法得到的
OpenerDirector
類的實(shí)例對(duì)象。
1.2 request常用子類
urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None):網(wǎng)絡(luò)資源請(qǐng)求的抽象。
- url,網(wǎng)絡(luò)資源地址字符串。
- data, 請(qǐng)求攜帶數(shù)據(jù),常為post表單數(shù)據(jù)。
- headers,攜帶請(qǐng)求頭,一些http常用請(qǐng)求頭信息。
- method,指明請(qǐng)求方法,GET、POST、PUT之類。
urllib.request.HTTPCookieProcessor(cookiejar=None):處理http cookie。
- cookiejar,一般為
cookielib.CookieJar()
方法保存的cookie文件。
urllib.request.ProxyHandler(proxies=None):代理請(qǐng)求。
- proxies,字典形式。如
{'sock5': 'localhost:1080'}
、{'https': '192.168.8.8:2365'}
。
urllib.request.FileHandler():一個(gè)文件對(duì)象。(不知是否可以作為上傳文件使用。)
這些子類又有一些自己的方法,大多暫且不介紹,附Request
類的方法官檔鏈接。
2、error
處理由request請(qǐng)求產(chǎn)生的錯(cuò)誤。
urllib.error.URLError:地址錯(cuò)誤,有屬性如下:
- reason,可能是錯(cuò)誤字符串或其它的錯(cuò)誤實(shí)例。
urllib.error.HTTPError:網(wǎng)絡(luò)請(qǐng)求錯(cuò)誤,有屬性如下:
- code,http狀態(tài)碼。
- reason,錯(cuò)誤原因。
- headers,響應(yīng)頭。
3、parse
The urllib.parse module defines functions that fall into two broad categories: URL parsing and URL quoting. These are covered in detail in the following sections.
這個(gè)模塊提供處理url的標(biāo)準(zhǔn)接口,兩種:解析處理和引用處理。
3.1 URL Parsing
The URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.
urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True):url地址解析。
url地址通常標(biāo)準(zhǔn)格式如下:scheme://netloc/path;parameters?query#fragment
詳細(xì)說(shuō)明介紹可見(jiàn)http.md
的介紹。返回是6個(gè)元素組成的元組。
- urlstring,urlstring地址字符串。
- scheme,指定默認(rèn)協(xié)議。
- allow_fragments,F(xiàn)alse時(shí)將不進(jìn)行fragment解析,直接將其視作path、query或parameters的一部分。
urllib.parse.parse_qs(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace'):解析url參數(shù)字符串。
- qs,查詢子串。
- keep_blank_values,百分比編碼查詢的空白值是否應(yīng)視為空白字符串。
- strict_parsing,如果解析錯(cuò)誤,false為默認(rèn)忽略,否則錯(cuò)誤引發(fā)ValueError異常。
- encoding,errors。可選的編碼和錯(cuò)誤參數(shù)指定如何將百分比編碼的序列解碼為Unicode字符。
3.2 URL Quoting
urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None, quote_via=quote_plus):多參數(shù)元組拼接為百分比編碼后的字符串。
4、寫在后面
概念比較空洞,實(shí)踐出真知。簡(jiǎn)單內(nèi)容可以參見(jiàn)threading_douban.py
。