Python3之urllib模塊
阿新 • • 發佈:2017-12-07
time fault request 方法 encode 數據格式 5.0 urn imp
簡介
urllib是python的一個獲取url(Uniform Resource Locators,統一資源定位符),可以用來抓取遠程的數據。
常用方法
(1)urlopen
urllib.request.urlopen(url, data=None,[timeout,]*,cafile=None,capath=None,cadefault=False,context=None)
urllib.request.urlopen() 可以獲取頁面,獲取頁面內容的數據格式為bytes類型,需要進行decode()解碼,轉換成str類型。
參數說明:
- url : 需要打開的網址
- data : 字典形式,默認為None時是GET方法,data不為空時, urlopen()的提交方式為POST,註意POST提交時,data需要轉換為字節;
- timeout : 設置網站訪問的超時時間
from urllib import request response = request.urlopen("http://members.3322.org/dyndns/getip") # <http.client.HTTPResponse object at 0x031F63B0> page = response.read() # b‘106.37.169.186\n‘ page = page.decode("utf-8") # ‘106.37.169.186\n‘
urlopen返回對象提供的方法:
- read(),readline(),readlines(),fileno(),close() : 對HTTPResponse類型數據進行操作
- info() : 返回HTTPMessage對象,表示遠程服務器返回的頭信息
- getcode() : 返回HTTP狀態碼,如果是http請求,200請求成功完成,404網頁未找到
- geturl(): 返回請求的url
(2)Request
urllib.request.Request(url,data=None,headers={},method=None)
from urllib import request url = r‘http://www.lagou.com/zhaopin/Python/?labelWords=label‘ headers = { ‘User-Agent‘: r‘Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ‘ r‘Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3‘, ‘Referer‘: r‘http://www.lagou.com/zhaopin/Python/?labelWords=label‘, ‘Connection‘: ‘keep-alive‘ } req = request.Request(url, headers=headers) page = request.urlopen(req).read() page = page.decode(‘utf-8‘)
(3)parse.urlencode
urllib.parse.urlencode(query, doseq=False,safe=‘‘,encoding=None,errors=None)
urlencode()的主要作用就是將url附上要提交的數據.
from urllib import request, parse url = r‘http://www.lagou.com/jobs/positionAjax.json?‘ headers = { ‘User-Agent‘: r‘Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ‘ r‘Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3‘, ‘Referer‘: r‘http://www.lagou.com/zhaopin/Python/?labelWords=label‘, ‘Connection‘: ‘keep-alive‘ } data = { ‘first‘: ‘true‘, ‘pn‘: 1, ‘kd‘: ‘Python‘ } data = parse.urlencode(data).encode(‘utf-8‘) # 此時data是字節 b‘first=true&pn=1&kd=Python‘ ,POST的數據必須是bytes或者iterable of bytes,不能是str,因此需要encode編碼 # 經過urlencode轉換後的data數據為‘first=true&pn=1&kd=Python‘ # 最後提交的url為:http://www.lagou.com/jobs/positionAjax.json?first=true?pn=1?kd=Python req = request.Request(url, headers=headers, data=data) # 此時req : <urllib.request.Request object at 0x02F52A30> page = request.urlopen(req).read() # 此時page是字節: b‘{"success":false,"msg":"\xe6\x82\xa8\xe6\x93\x8d\xe4\xbd\x9c\xe5\xa4\xaa\xe9\xa2\x91\xe7\xb9\x81,\xe8\xaf\xb7\xe7\xa8\x8d\xe5\x90\x8e\xe5\x86\x8d\xe8\xae\xbf\xe9\x97\xae","clientIp":"106.37.169.186"}\n page = page.decode(‘utf-8‘) # 此時page是字符串:"success":false,"msg":"您操作太頻繁,請稍後再訪問","clientIp":"106.37.169.186"}
(4)代理 request.ProxyHandler(proxies=None)
當需要抓取的網站設置了訪問限制,這時就需要用到代理來抓取數據。
from urllib import request, parse data = { ‘first‘: ‘true‘, ‘pn‘: 1, ‘kd‘: ‘Python‘ } proxy = request.ProxyHandler({‘http‘: ‘5.22.195.215:80‘}) # 設置proxy opener = request.build_opener(proxy) # 掛載opener request.install_opener(opener) # 安裝opener data = parse.urlencode(data).encode(‘utf-8‘) page = opener.open(url, data).read() page = page.decode(‘utf-8‘) return page
文章參考:https://www.cnblogs.com/Lands-ljk/p/5447127.html
Python3之urllib模塊