requests请求库练习--GitHub登录

# coding = utf-8
"""
结合抓包工具,采用两种方法模拟登录github
直接利用session登录和利用requests登录
""" import requests import re # 设置请求头,伪装为浏览器 headers = { 'Host': 'github.com', 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'Origin': 'https://github.com', 'Upgrade-Insecure-Requests': '1', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36', '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,en;q=0.8', } def get_info(): """ 访问github页面,获取post提交时所需要的参数 :return: """ url = 'https://github.com/login' r = requests.get(url, verify=False) # 返回访问github后得到的源码 text = r.text # 通过正则,匹配post提交时需要提交的参数 # 通过抓包工具分析,此处需要token参数 token = re.findall(r'<input type="hidden" name="authenticity_token" value="(.*?)" />', text, re.S) return r.cookies, token[0] if __name__ == '__main__': # """ # 通过使用session和requests两种方法来模拟登陆github, # """ # # 方法一:通过session登陆 # # 创建session,保持会话 # session = requests.session() # # # 访问登录页面,获取cookies # rr = session.get('https://github.com/login', verify=False) # # # 通过正则匹配变化参数token值 # token = re.findall(r'<input type="hidden" name="authenticity_token" value="(.*?)" />', rr.text, re.S) # # # 通过抓包工具,分析提交参数,并将其中的变化参数修改为代码获取的 # # 例如token参数 # data = { # 'utf8': ' ✓', # 'password': 'zhao0.0002', # 'login': 'zInPython', # 'commit': 'Sign in', # 'authenticity_token': token[0], # } # # # 访问参数提交的目标地址,并将需要参数传入 # post_url = 'https://github.com/session' # r = session.post(post_url, data=data, headers=headers, verify=False) # # # 返回登录成功后的源码 # print(r.text) # 方法二:通过requests访问github # 获取cookie和可变参数 cookies, token = get_info() # 构造post提交需要的参数 data = { 'utf8': '', 'password': 'zhao0.0002', 'login': 'zInPython', 'commit': 'Sign in', 'authenticity_token': token, } # 访问登录提交参数网址 post_url = 'https://github.com/session' r = requests.post(post_url, data=data, headers=headers, cookies=cookies, verify=False) # 登录成功后的源码 print(r.text)
原文地址:https://www.cnblogs.com/pythoner6833/p/8997393.html