前言:
什么是cookie?
Cookie,指某些網站為了辨別用戶身份、進行session跟蹤而儲存在用戶本地終端上的數據(通常經過加密)。
比如說有些網站需要登錄后才能訪問某個頁面,在登錄之前,你想抓取某個頁面內容是不允許的。那么我們可以利用Urllib庫保存我們登錄的Cookie,然后再抓取其他頁面,這樣就達到了我們的目的。
一、Urllib庫簡介
Urllib是python內置的HTTP請求庫,官方地址:https://docs.python.org/3/library/urllib.html
包括以下模塊:
>>>urllib.request 請求模塊 >>>urllib.error 異常處理模塊 >>>urllib.parse url解析模塊 >>>urllib.robotparser robots.txt解析模塊
二、urllib.request.urlopen介紹
uurlopen一般常用的有三個參數,它的參數如下:
urllib.requeset.urlopen(url,data,timeout)
簡單的例子:
1、url參數的使用(請求的URL)
response = urllib.request.urlopen('http://www.baidu.com')
2、data參數的使用(以post請求方式請求)
data= bytes(urllib.parse.urlencode({'word':'hello'}), encoding='utf8') response= urllib.request.urlopen('http://www.baidu.com/post', data=data)
3、timeout參數的使用(請求設置一個超時時間,而不是讓程序一直在等待結果)
response= urllib.request.urlopen('http://www.baidu.com/get', timeout=4)
三、構造Requset
1、數據傳送POST和GET(舉例說明:此處列舉登錄的請求,定義一個字典為values,參數為:email和password,然后利用urllib.parse.urlencode方法將字典編碼,命名為data,構建request時傳入兩個參數:url、data。運行程序,即可實現登陸。)
GET方式:直接以鏈接形式訪問,鏈接中包含了所有的參數。
LOGIN_URL= "http://*******/postLogin/" values={'email':'*******@***com','password':'****'} data=urllib.parse.urlencode(values).encode() geturl = LOGIN_URL+ "?"+data request = urllib.request.Request(geturl)
POST方式:上面說的data參數就是用在這里的,我們傳送的數據就是這個參數data。
LOGIN_URL='http://******/postLogin/' values={'email':'*******@***.com','password':'*****'} data=urllib.parse.urlencode(values).encode() request=urllib.request.Request(URL,data)
2、設置Headers(有些網站不會同意程序直接用上面的方式進行訪問,如果識別有問題,那么站點根本不會響應,所以為了完全模擬瀏覽器的工作,我們需要設置一些Headers 的屬性)

舉例:(這個例子只是說明了怎樣設置headers)
user_agent = r'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0' headers={'User-Agent':user_agent,'Connection':'keep-alive'} request=urllib.request.Request(URL,data,headers)
四、使用cookie登錄
1、獲取登錄網址
瀏覽器輸入需要登錄的網址:'http://*****/login'(注意:這個並非其真實站點登錄網址),使用抓包工具fiddler抓包(其他工具也可)找到登錄后看到的request。
此處確定需要登錄的網址為:'http://*****/postLogin/'

2、查看要傳送的post數據
找到登錄后的request中有webforms的信息,會列出登錄要用的post數據,包括Email,password,auth。
找到登錄后看到的request的headers信息,找出User-Agent設置、connection設置等
4、開始編碼,使用cookie登錄該網站
import urllib.error, urllib.request, urllib.parse import http.cookiejar LOGIN_URL = 'http://******/postLogin' #get_url為使用cookie所登陸的網址,該網址必須先登錄才可 get_url = 'https://*****/pending' values = {'email':'*****','password':'******','auth':'admin'} postdata = urllib.parse.urlencode(values).encode() user_agent = r'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36' \ r' (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36' headers = {'User-Agent':user_agent, 'Connection':'keep-alive'} #將cookie保存在本地,並命名為cookie.txt cookie_filename = 'cookie.txt' cookie_aff = http.cookiejar.MozillaCookieJar(cookie_filename) handler = urllib.request.HTTPCookieProcessor(cookie_aff) opener = urllib.request.build_opener(handler) request = urllib.request.Request(LOGIN_URL, postdata, headers) try: response = opener.open(request) except urllib.error.URLError as e: print(e.reason) cookie_aff.save(ignore_discard=True, ignore_expires=True) for item in cookie_aff: print('Name ='+ item.name) print('Value ='+ item.value) #使用cookie登陸get_url get_request = urllib.request.Request(get_url,headers=headers) get_response = opener.open(get_request) print(get_response.read().decode())
5、反復使用cookie登錄
(上面代碼中我們保存cookie到本地了,以下代碼我們能夠直接從文件導入cookie進行登錄,不用再構建request了)
import urllib.request, urllib.parse import http.cookiejar get_url = 'https://******/pending' cookie_filename = 'cookie.txt' cookie_aff = http.cookiejar.MozillaCookieJar(cookie_filename) cookie_aff.load(cookie_filename,ignore_discard=True,ignore_expires=True) handler = urllib.request.HTTPCookieProcessor(cookie_aff) opener = urllib.request.build_opener(handler) #使用cookie登陸get_url get_request = urllib.request.Request(get_url) get_response = opener.open(get_request) print(get_response.read().decode())
以上