1.基本方法
urllib.request.``urlopen
(url, data=None, [timeout, ]***, cafile=None, capath=None, cadefault=False, context=None)
url: 需要打開的網(wǎng)址
data:Post提交的數(shù)據(jù)
timeout:設(shè)置網(wǎng)站的訪問(wèn)超時(shí)時(shí)間
直接用urllib.request模塊的urlopen()獲取頁(yè)面双戳,page的數(shù)據(jù)格式為bytes類型绘梦,需要decode()解碼马绝,轉(zhuǎn)換成str類型忆谓。
<pre>1 from urllib import request 2 response = request.urlopen(r'http://python.org/') # <http.client.HTTPResponse object at 0x00000000048BC908> HTTPResponse類型
3 page = response.read() 4 page = page.decode('utf-8')</pre>
urlopen返回對(duì)象提供方法:
read() , readline() ,readlines() , fileno() , close() :對(duì)HTTPResponse類型數(shù)據(jù)進(jìn)行操作
info():返回HTTPMessage對(duì)象么伯,表示遠(yuǎn)程服務(wù)器返回的頭信息
getcode():返回Http狀態(tài)碼填大。如果是http請(qǐng)求,200請(qǐng)求成功完成;404網(wǎng)址未找到
geturl():返回請(qǐng)求的url
2.使用Request
urllib.request.``Request
(url, data=None, headers={}, method=None)
使用request()來(lái)包裝請(qǐng)求蒸播,再通過(guò)urlopen()獲取頁(yè)面匿醒。
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')
用來(lái)包裝頭部的數(shù)據(jù):
User-Agent :這個(gè)頭部可以攜帶如下幾條信息:瀏覽器名和版本號(hào)场航、操作系統(tǒng)名和版本號(hào)、默認(rèn)語(yǔ)言
Referer:可以用來(lái)防止盜鏈廉羔,有一些網(wǎng)站圖片顯示來(lái)源http://***.com溉痢,就是檢查Referer來(lái)鑒定的
Connection:表示連接狀態(tài),記錄Session的狀態(tài)。
3.Post數(shù)據(jù)
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
urlopen()的data參數(shù)默認(rèn)為None孩饼,當(dāng)data參數(shù)不為空的時(shí)候髓削,urlopen()提交方式為Post。
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')
req = request.Request(url, headers=headers, data=data)
page = request.urlopen(req).read()
page = page.decode('utf-8')
urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None)
urlencode()主要作用就是將url附上要提交的數(shù)據(jù)镀娶。
data = {
'first': 'true',
'pn': 1,
'kd': 'Python'
}
data = parse.urlencode(data).encode('utf-8')
經(jīng)過(guò)urlencode()轉(zhuǎn)換后的data數(shù)據(jù)為?first=true?pn=1?kd=Python立膛,最后提交的url為
http://www.lagou.com/jobs/positionAjax.json?first=true?pn=1?kd=Python
Post的數(shù)據(jù)必須是bytes或者iterable of bytes,不能是str梯码,因此需要進(jìn)行encode()編碼
1 page = request.urlopen(req, data=data).read()
當(dāng)然宝泵,也可以把data的數(shù)據(jù)封裝在urlopen()參數(shù)中
4.異常處理
def get_page(url):
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')
req = request.Request(url, headers=headers)
try:
page = request.urlopen(req, data=data).read()
page = page.decode('utf-8')
except error.HTTPError as e:
print(e.code())
print(e.read().decode('utf-8'))
return page
5、使用代理
urllib.request.``ProxyHandler
(proxies=None)
當(dāng)需要抓取的網(wǎng)站設(shè)置了訪問(wèn)限制忍些,這時(shí)就需要用到代理來(lái)抓取數(shù)據(jù)鲁猩。
data = {
'first': 'true',
'pn': 1,
'kd': 'Python'
}
proxy = request.ProxyHandler({'http': '5.22.195.215:80'}) # 設(shè)置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