1.使用urllib發(fā)起請(qǐng)求
from urllib import request
import ssl
2.目標(biāo)url
url = 'http://www.baidu.com/'
3.request.urlopen():使用urlopen方法模擬瀏覽器發(fā)起請(qǐng)求
"""
url, 請(qǐng)求的目標(biāo)url地址
data=None,默認(rèn)情況為None,表示發(fā)起的是一個(gè)get請(qǐng)求,不為None,則發(fā)起的是一個(gè)post請(qǐng)求
timeout=,設(shè)置請(qǐng)求的超時(shí)時(shí)間
cafile=None, 設(shè)置證書
capath=None, 設(shè)置證書路徑
cadefault=False, 是否要使用默認(rèn)證書(默認(rèn)為False)
context=None:是一個(gè)ssl值,表示忽略ssl認(rèn)證
"""
4.是一個(gè)ssl值,表示忽略ssl認(rèn)證(如果請(qǐng)求出現(xiàn)了ssl證書認(rèn)證錯(cuò)誤,
5.我們就需要設(shè)置ssl._create_unverified_context(),忽略證書認(rèn)證)
content = ssl._create_unverified_context()
response = request.urlopen(url,timeout=10,content=content)
6.從response響應(yīng)結(jié)果中獲取參數(shù)
7.狀態(tài)碼
code = response.status
print(code)
8.獲取頁面源碼的二進(jìn)制數(shù)據(jù)
b_html = response.read()
print(type(b_html),len(b_html))
9.獲取響應(yīng)的響應(yīng)頭部(Response Headers)
res_headers = response.getheaders()
print(res_headers)
10.獲取響應(yīng)頭中指定參數(shù)的值
cookie_data = response.getheader('Set-Cookie')
print(cookie_data)
11.reason返回一個(gè)響應(yīng)結(jié)果的原因
reason = response.reason
print(reason)
12.將獲取到的二進(jìn)制數(shù)據(jù),轉(zhuǎn)換為字符串decode
str_html = b_html.decode('utf-8')
print(type(str_html))
with open('b_baidu.page.html','w') as file:
# file.write(b_html)
file.write(str_html)
13.如果請(qǐng)求要攜帶請(qǐng)求頭
14.需要先構(gòu)建一個(gè)request對(duì)象
"""
url:發(fā)起請(qǐng)求的url地址
data=None, 默認(rèn)情況為None,表示發(fā)起的是一個(gè)get請(qǐng)求,不為None,則發(fā)起的是一個(gè)post請(qǐng)求
headers={},設(shè)置請(qǐng)求頭(headers對(duì)應(yīng)的數(shù)據(jù)類型是一個(gè)字典)
origin_req_host=None, (指定發(fā)起請(qǐng)求的域)
unverifiable=False,忽略SSL認(rèn)證
method=None:指定發(fā)起請(qǐng)求的方式
"""
req_header = {
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
req = request.Request(url,headers=req_header)
15.根據(jù)構(gòu)建的req請(qǐng)求對(duì)象發(fā)起請(qǐng)求
response = request.urlopen(req)
response.status
response.read()
response.getheaders()
response.getheader('Server')
response.reason
16.str和bytes數(shù)據(jù)類型
python2中:對(duì)于字符串和bytes類型的數(shù)據(jù)沒有明顯的區(qū)分
python3中:對(duì)于字符串和bytes類型的數(shù)據(jù)有明顯的區(qū)分
將bytes類型的數(shù)據(jù)轉(zhuǎn)換為字符串使用decode('編碼類型')
將字符串轉(zhuǎn)換為bytes類型的數(shù)據(jù)使用encode('編碼類型')
bytearray和bytes類型的數(shù)據(jù)是有區(qū)別的:前者是可變的,后者是不可變的