paython爬取github登入頁面token資訊並登入github
阿新 • • 發佈:2019-01-25
1.語言:
Python3.5
2.用到的庫:
requests
re(正則)
3.流程:
手動登入檢視需要的引數,觀察一次登入傳送的請求
登入過程如下:
***** *** * 發現除了一個token是動態的,其他的都是輸入或是固定的。
頁面查詢token:
引數如下:
'login':'。。。',
'password':'。。。',
'authenticity_token':token,
'commit':'Sign in',
'utf8': "✓"}
*****
***
*
用正則在登入頁面爬取登入用的token, 並賦值到引數裡
*****
***
*
接著用會話物件去傳送帶有引數的資料到url
*****
***
*
完成
4.程式碼:
# -*- coding:utf-8 -*- import requests import re ''' 用到的庫: requests re(正則) 流程: 手動登入檢視需要的引數,觀察一次登入傳送的請求 ***** *** * 發現除了一個token是動態的,其他的都是輸入或是固定的。引數如下: 'login':'。。。', 'password':'。。。', 'authenticity_token':token, 'commit':'Sign in', 'utf8': "✓"} ***** *** * 用正則在登入頁面爬取登入用的token,並賦值到引數裡 ***** *** * 接著用會話物件去傳送帶有引數的資料到url ***** *** * 完成 ''' s = requests.Session()#獲取會話物件,用於登入時的cookie和session header = {'Host': 'github.com', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:47.0) Gecko/20100101 Firefox/47.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Referer': 'https://github.com', 'Connection': 'keep-alive'} indexUrl = 'https://github.com/'#首頁地址 loginUrl = 'https://github.com/login'#登入頁面 sessionUrl = 'https://github.com/session'#登入頁面把表單提交到這個url,然後重定向到首頁,把資料提交到這個Url之後可以獲取到cookie,用於登入 ##>>> payload = {'key1': 'value1', 'key2': 'value2'} ##>>> r = requests.get("http://httpbin.org/get", params=payload) tokenRule = '<input name="authenticity_token" type="hidden" value="(.*?)"'#登入引數裡面有一個token引數,是載入到頁面中並且是動態的,需要爬出來 loginHtml = s.get(loginUrl,headers=header)#得到登入頁面 tokenPattern = re.compile(tokenRule,re.S) arraryTolen = re.findall(tokenPattern,loginHtml.text)#得到動態的token,這裡返回的事陣列,取第一個 #print(loginHtml.text) token = arraryTolen[0] print("the token is: ",token) loginParams = {'login':'*****', 'password':'******', 'authenticity_token':token, 'commit':'Sign in', 'utf8': "✓"}#配置登入引數 sessionHtml = s.post(sessionUrl,data=loginParams)#得到登入後的頁面,其實被定位到了首頁 ''' 輸出是否登入成功,如果不成功返回狀態碼和原因,以及詳細的錯誤頁面 ''' print("the session rsult is: ",sessionHtml.status_code) print("the reason is: ",sessionHtml.reason) print("the detail is: ",sessionHtml.text) indexhtml = s.get('https://github.com/HanlaoTwo/StacknotOverFlow',headers=header)#可以繼續用這個會話物件去訪問需要登入的頁面 print(indexhtml.text)
5.原始碼:
https://github.com/HanlaoTwo/StacknotOverFlow/blob/master/loginGit.py