# -*- coding: utf-8 -*-
# @author: criselyj
# @date:  2020-08-14 12:13:11

import re
import requests


class githublogin(object):

  def __init__(self, email, password):
    # 初始化信息
    self.headers = {
      'user-agent': 'mozilla/5.0 (macintosh; intel mac os x 10_14_2) applewebkit/537.36 (khtml, like gecko) chrome/71.0.3578.98 safari/537.36',
      'referer': 'https://github.com/',
      'host': 'github.com'
    }

    self.session = requests.session()
    self.login_url = 'https://github.com/login'
    self.post_url = 'https://github.com/session'
    self.email = email
    self.password = password

  def login_github(self):
    # 登录入口
    post_data = {
      'commit': 'sign in',
      'utf8': '',
      'authenticity_token': self.get_token(),
      'login': self.email,
      'password': self.password
    }
    resp = self.session.post(
      self.post_url, data=post_data, headers=self.headers)
    
    print('statuscode:', resp.status_code)
    if resp.status_code != 200:
      print('login fail')
    match = re.search(r'"user-login" content="(.*?)"', resp.text)
    user_name = match.group(1)
    print('username:', user_name)



  # get login token
  def get_token(self):

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

    if response.status_code != 200:
      print('get token fail')
      return none
    match = re.search(
      r'name="authenticity_token" value="(.*?)"', response.text)
    if not match:
      print('get token fail')
      return none
    return match.group(1)


if __name__ == '__main__':
  email = input('account:')
  password = input('password:')

  login = githublogin(email, password)
  login.login_github()

登录效果

以上就是python 模拟登陆github的示例代码的详细内容,更多关于python 模拟登陆github的资料请关注www.887551.com其它相关文章!