筆記-爬蟲-模擬登陸github

筆記-模擬登陸github

1.      模擬登陸github

1.1.    環境準備

安裝/升級requests 2.20.0html

pip install --upgrade requestsgit

pip show requestsgithub

 

1.2.    分析登陸過程及模擬

  1. 在chome打開github.com/login,按f12,選中network>preserver log(表示持續日誌),進入調試模式。
  2. 找到登陸頁面:

檢查發現login頁面輸入內容回車後會跳轉頁面,其實是由github.com/session頁面接收數據並完成登陸。web

  1. 構造請求包:

接下來就是構造請求了,包括headers和form data兩部分;cookie

頭部構造已經很熟悉了,主要是注意不要漏掉一些字段,包括referer,Origin等,實際上在session頁面的post頭部中要包含有login頁面返回的cookie,但Session會自動完成這個過程,因此不須要手動指定了。session

字段全一些能夠下降被反爬的機率。app

form data分爲兩部分,固定部分無所謂,但有一個字段authenticity_token是由login頁面返回,經過正則找到它便可。post

  1. 發送請求,獲得應答;

登陸成功後會自動重定向到首頁,此時已經作到了session 的狀態保持。url

  1. 驗證登陸成功。

 

1.3.    問題

在post登陸請求後老是返回422:調試

錯誤碼錶明請求格式正確,但含有語義錯誤,沒法響應。

檢查發現authenticity_token拼寫錯,改正後正常。

 

1.4.    代碼實現

#coding:utf-8

'''

模擬登陸github

'''

 

import copy

import requests

from lxml import etree

 

 

class Login():

    def __init__(self):

        self.headers = {

            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',

            'Accept-Encoding':'gzip, deflate, br',

            'Accept-Language':'zh-CN,zh;q=0.9',

            'Cache-Control':'max-age=0',

            'Connection':'keep-alive',

            'Host':'github.com',

            'Upgrade-Insecure-Requests':'1',

            'User-Agent':'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'

            }

 

        self.login_url = 'https://github.com/login'

        self.post_url = 'https://github.com/session'

        self.profileUrl = 'https://github.com/settings/profile'

        self.session = requests.Session()

 

 

    def _token(self):

        '''

        parse for token.

        '''

        response = self.session.get(self.login_url, headers=self.headers)

        selector = etree.HTML(response.text)

        token = selector.xpath('//div//input[2]/@value')[0]

        return token

 

    def login(self, username, password):

        post_data = {

            'commit':'Sign in',

            'utf-8':'✓',

            'authenticity_token':self._token(),

            'login':username,

            'password':password

            }

        header_temp = copy.copy(headers)

        header_add = {'Referer':r.url,'Origin':'https://github.com'}

        header_temp.update(header_add)

       

        response = self.session.post(self.post_url, headers=header_temp, data= post_data)

 

def islogin(self):

      ‘’’登陸成功驗證。’’’

        try:

            response = self.session.get(self.profileUrl, headers=self.headers)

        except:

            print('get page failed!')

 

        selector = etree.HTML(response.text)

        flag = selector.xpath('//div[@class="column two-thirds"]/dl/dt/label/text()')

        info = selector.xpath('//div[@class="column two-thirds"]/dl/dd/input/@value')

        textarea = selector.xpath('//div[@class="column two-thirds"]/dl/dd/textarea/text()')

        # 登錄成功返回來的我的設置信息

        print(u'我的設置Profile標題: %s'%flag)

        print(u'我的設置Profile內容: %s'%info)

        print(u'我的設置Profile內容: %s'%textarea)

 

 

if __name__ == '__main__':

    login = Login()

    login.login(username='username’, password='password')

    login.islogin()

相關文章
相關標籤/搜索