python爬蟲-使用cookie登陸

前言:

什麼是cookie?html

Cookie,指某些網站爲了辨別用戶身份、進行session跟蹤而儲存在用戶本地終端上的數據(一般通過加密)。python

好比說有些網站須要登陸後才能訪問某個頁面,在登陸以前,你想抓取某個頁面內容是不容許的。那麼咱們能夠利用Urllib庫保存咱們登陸的Cookie,而後再抓取其餘頁面,這樣就達到了咱們的目的。web


1、Urllib庫簡介

Urllib是python內置的HTTP請求庫,官方地址:https://docs.python.org/3/library/urllib.html瀏覽器

包括如下模塊:服務器

>>>urllib.request 請求模塊

>>>urllib.error 異常處理模塊

>>>urllib.parse url解析模塊

>>>urllib.robotparser robots.txt解析模塊

 


2、urllib.request.urlopen介紹

uurlopen通常經常使用的有三個參數,它的參數以下:cookie

urllib.requeset.urlopen(url,data,timeout)

簡單的例子:session

一、url參數的使用(請求的URL)工具

response = urllib.request.urlopen('http://www.baidu.com')

二、data參數的使用(以post請求方式請求)post

data= bytes(urllib.parse.urlencode({'word':'hello'}), encoding='utf8')

response= urllib.request.urlopen('http://www.baidu.com/post', data=data)

三、timeout參數的使用(請求設置一個超時時間,而不是讓程序一直在等待結果)網站

response= urllib.request.urlopen('http://www.baidu.com/get', timeout=4)

 


3、構造Requset

一、數據傳送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)

 

二、設置Headers(有些網站不會贊成程序直接用上面的方式進行訪問,若是識別有問題,那麼站點根本不會響應,因此爲了徹底模擬瀏覽器的工做,咱們須要設置一些Headers 的屬性)


 
上圖能夠看到該請求的headers,這個頭中包含了許多信息:Cache、Client、Transport等等。其中,agent就是請求的身份,若是沒有寫入請求身份,那麼服務器不必定會響應,因此能夠在headers中設置agent。

舉例:(這個例子只是說明了怎樣設置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)

 


4、使用cookie登陸

一、獲取登陸網址

瀏覽器輸入須要登陸的網址:'http://*****/login'(注意:這個並不是其真實站點登陸網址),使用抓包工具fiddler抓包(其餘工具也可)找到登陸後看到的request。

此處肯定須要登陸的網址爲:'http://*****/postLogin/'


 

二、查看要傳送的post數據

找到登陸後的request中有webforms的信息,會列出登陸要用的post數據,包括Email,password,auth。

 
三、查看headers信息

找到登陸後看到的request的headers信息,找出User-Agent設置、connection設置等

 

四、開始編碼,使用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())

 

五、反覆使用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())

 


 

以上

相關文章
相關標籤/搜索