溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

利用Python模擬GitHub登錄的示例

發布時間:2021-02-03 15:22:57 來源:億速云 閱讀:162 作者:小新 欄目:開發技術

這篇文章給大家分享的是有關利用Python模擬GitHub登錄的示例的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

Fiddler抓包分析

首先,我們想要模擬一個網站的登錄,我們必須要簡單了解其大致過程。
在這里,我通過Fiddler來抓取GitHub登錄的請求,從網頁上登錄的URL為:https://github.com/login ,抓包結果如下:

利用Python模擬GitHub登錄的示例

左邊的是會話列表,右邊的是請求和響應的數據。一般情況下,登錄都是用POST請求,因為我在左邊的會話列表中設置了顯示RequestMethod一列,因此能夠很方便的找到POST請求。當然,Fiddler默認不顯示RequestMethod,如果沒有設置,還可以通過命令“=post”來快速過濾POST請求。

利用Python模擬GitHub登錄的示例

在GitHub登錄時,我們通過抓包發現,GitHub登錄的URL雖然時https://github.com/login,但發生了302重定向,其真正提交POST表單數據的URL是 https://github.com/session ,當登錄成功時,則會跳轉到 https://github.com/ 首頁。

打開WebForm,我們可以看到POST表單數據提交的值,可以發現,只有authenticity_token、login、password三個字段是會變化的,其余的每次登錄都是固定的值。而login、password分別是我們登錄的用戶和密碼,因此我們只需要分析出 authenticity_token 從何而來,便可以實現模擬登錄了。

至于如何確定 authenticity_token 從哪個頁面返回的,我們直接在響應數據中搜索就行了,或者把數據復制出來再進行搜索。最后我們會發現,authenticity_token 是在 https://github.com/login 這個請求中返回的,只不過用 hidden 隱藏起來了。

利用Python模擬GitHub登錄的示例

好了,到目前大致流程我們已經梳理清楚了,接下來我們便通過Python來實現模擬GitHub登錄。

代碼實現

本人環境:PyCharm 2018.2.4、Python3.7.0

1. 設置請求頭和Session

# 設置Session
    self.s = requests.session()
    # 設置請求頭
    self.headers = {
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:44.0) Gecko/20100101 Firefox/44.0"
    }
    # 在使用Fiddler時進行請求,通過該代碼忽略SSLError錯誤
    self.s.verify = False

在這里,我們設置了Session會話對象,Session相當于1個微型瀏覽器,能夠自動幫我們保持請求中的某些參數(如cookies),有了它,我們一般不需要額外去處理cookies、header等。
假如我們是在Fiddler打開的狀態下,通過代碼進行請求,那么將會遇到SSLError的錯誤,而當加上 self.s.verify = False 這行代碼后,我們便可以忽略該錯誤。

requests.exceptions.SSLError: HTTPSConnectionPool(host='github.com', port=443): Max retries exceeded with url: /login (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1045)')))

注意:

我們通過上面的代碼忽略了SSLError的錯誤后,再次運行,這時仍然會出現2行警告,這2個警告并不影響我們的登錄,可以不管它。

D:\Python\installation\lib\site-packages\urllib3\connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
 InsecureRequestWarning)
D:\Python\installation\lib\site-packages\urllib3\connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
 InsecureRequestWarning)

如果我們想去掉這2行警告,也可以通過如下代碼來解決(針對Python3):

import urllib3
urllib3.disable_warnings()

2. 獲取authenticity_token

login_url = "https://github.com/login"
    r = self.s.get(login_url, headers = self.headers)
    authenticity_token = re.findall('<input type="hidden" name="authenticity_token" value="(.+?)" />', r.text)
    print("authenticity_token:{}".format(authenticity_token))
    return authenticity_token[1]

當我們訪問 https://github.com/login 時,登錄界面會生成隱藏參數authenticity_token,而這恰是我們在登錄提交表單時需要用到的參數。我們可通過正則表達式 re.findall 來獲取authenticity_token。另外,我們還會發現,HTML界面中存在2個authenticity_token,因此通過正則返回的是一個長度為2的列表,經過分析,GitHub在登錄時用到的是列表中的第二個元素,即authenticity_token[1]。

3. 模擬登錄

  def github_login(self, authenticity_token, username, password):
    session_url = "https://github.com/session"
    body = {
      "authenticity_token":authenticity_token,
      "commit":"Sign in",
      "login":username,
      "password":password,
      "utf8":"?",
      "webauthn-support":"unknown"
    }
    r = self.s.post(session_url, headers = self.headers, data = body)
    title = re.findall('<title>(.+?)</title>',r.text)
    print("title:%s" %title[0])
    return title[0]

我們在上面得到authenticity_token后,便可以來實現登錄了。通過POST請求提交表單后,我們需要判斷是否登錄成功。在這里,我是通過頁面的標題來判斷GitHub是否登錄成功,當然,還有許多方法可以用于判斷。

4. 通過 title 判斷是否登錄成功

  def is_login_success(self, title):
    if "GitHub" == title:
      return True
    else:
      return False

GitHub登錄成功后,界面的標題會顯示"GitHub",而登錄失敗時,一般顯示的標題則是"Sign in to GitHub · GitHub"。

OK,以上就是通過Python模擬GitHub登錄的過程,難度不大,相信大多數人閱讀后都應該可以進行實踐。

附源碼:

import requests
import re
import urllib3
urllib3.disable_warnings()

class Github_Login():

  def __init__(self):
    # 設置Session
    self.s = requests.session()
    # 設置請求頭
    self.headers = {
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:44.0) Gecko/20100101 Firefox/44.0"
    }
    # 在使用Fiddler時進行請求,通過該代碼忽略SSLError錯誤
    self.s.verify = False

  # 獲取 authenticity_token
  def get_authenticity_token(self):
    login_url = "https://github.com/login"
    r = self.s.get(login_url, headers = self.headers)
    authenticity_token = re.findall('<input type="hidden" name="authenticity_token" value="(.+?)" />', r.text)
    print("authenticity_token:{}".format(authenticity_token))
    return authenticity_token[1]

  # 模擬登錄,并返回 title
  def github_login(self, authenticity_token, username, password):
    session_url = "https://github.com/session"
    body = {
      "authenticity_token":authenticity_token,
      "commit":"Sign in",
      "login":username,
      "password":password,
      "utf8":"?",
      "webauthn-support":"unknown"
    }
    r = self.s.post(session_url, headers = self.headers, data = body)
    title = re.findall('<title>(.+?)</title>',r.text)
    print("title:%s" %title[0])
    return title[0]

  # 通過 title 判斷是否登錄成功
  def is_login_success(self, title):
    if "GitHub" == title:
      return True
    else:
      return False

if __name__ == '__main__':
  github = Github_Login()
  authenticity_token = github.get_authenticity_token()
  title = github.github_login(authenticity_token, username = "用戶名", password = "密碼")
  login_result = github.is_login_success(title)
  print(login_result)

感謝各位的閱讀!關于“利用Python模擬GitHub登錄的示例”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女