對於互聯網數據,Python 有不少處理網絡協議的工具,urllib 是很經常使用的一種。html
1、urllib.request,request 能夠很方便的抓取 URL 內容。python
參數:url=‘http://www.baidu.com’,請求的 url。json
data=None,請求的數據,無關緊要,bytes 類型。cookie
timeout=3,設置訪問超時時間,無關緊要 網絡
cafile=None,HTTPS 請求 CA 證書工具
capath=None,CA 證書 pathpost
context=None,指定 SSL 設置,無關緊要,ssl.SSLContext 類型ui
參數:url,請求 url。 url
data=None,請求參數,無關緊要spa
headers={},請求 header 參數。
origin_req_host=None,請求 host 或 IP
unverifiable=False,代表請求是否沒法驗證,默認爲 false
method=None,請求方法,get、post、put 等
from urllib import request,parse #url url = 'http://fanyi.baidu.com/sug' #request data data = {'kw': 'python'} data = parse.urlencode(data).encode('utf-8') #proxy proxy = {'http': '120.194.18.90:81'} proxy_handler = request.ProxyHandler(proxy) opener = request.build_opener(proxy_handler) request.install_opener(opener) #headers = { # 'Content-Length': len(data), # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0' #} #req = request.Request(url=base_url, data=data, headers=headers) req = request.Request(base_url, data) req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0') rsp = request.urlopen(req) result = rsp.read().decode('utf-8') print(result)
#rsp 的屬性 print('返回數據類型: {}'.format(type(rsp))) print('返回數據信息: {}'.format(rsp)) print('header 信息: {}'.format(rsp.info())) print('header 信息: {}'.format(rsp.getheaders())) print('header 屬性信息: {}'.format(rsp.getheader('Server'))) print('響應狀態信息: {}'.format(rsp.status)) print('響應狀態信息: {}'.format(rsp.getcode())) print('響應的 URL: {}'.format(rsp.geturl()))
#cookie 操做 from urllib import request from http impot cookiejar #獲取 cookie cookie = cookiejar.CookieJar() handler = request.HTTPCookieProcessor(cookie) opener = request.build_opener(handler) rsp = opener.open('http://www.baidu.com') res = rsp.read().decode('utf-8') print(res) #保存 cookie #FileCookieJar、MozillaCookieJar、LWPCookieJar,不一樣的保存格式 filename = 'cookie.txt' cookie = cookiejar.MozillaCookieJar(filename) handler = request.HTTPCookieProcessor(cookie) opener = request.build_opener(handler) rsp = opener.open('http://www.baidu.com') cookie.save(igonre_discard=True, ignore_expires=True) #使用 cookie cookie cookiejar.MozillaCookieJar() cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True) handler = request.HTTPCookieProcessor(cookie) opener = request.build_opener(handler) rsp = opener.open('http://www.baidu.com') res = rsp.read().decode('utf-8') print(res)
2、urllib.parse
參數:
url,訪問 url
scheme,解析協議,https、http
allow_fragments=False,是夠帶有查詢參數
#1 url = 'https://www.baidu.com/s?' qs = {'wd':'python'} qs = urllib.parse.urlparse(qs) full_url = url + qs #2 url = urllib.parse.urlparse('http://www.baidu.com/s?wd=python') print(url) #3 data = ['http', 'www.baidu.com', 's', 'wd=python'] print(urllib.parse.urlunparse(data)) #4 print(urllib.parse.urljson('http://www.baidu.com', 'index.html'))
3、urllib.error
經過 try...except 能夠捕捉異常,error 分爲 HTTPError,URLError
try: res = urllib.request.urlopen(url).open().decode('utf-8') print(res) except urllib.error.URLError as e: print(e) except urllib.error.HTTPError as e: print(e) except Exception as e: print(e)
4、urllib.robotparser