开发者工具分析请求
从session请求分析得知:
1.请求的URL为:https://github.com/session
2.该请求为post请求,即需要上传data表单,所以我们需要分析form-data
由form-data分析得知:
1.login:GitHub的账号
2.password:GitHub的密码
3.authenticity_token:每次请求时都发生变动
4.其余参数没有特殊的变动
因此需要分析authenticity_token的规律,经过分析源代码得知:
在login页面中存在该参数,且每次请求该页面时该参数都发生变动
因此我们需要使用维持会话的方式抓取该参数
import requests session = requests.Session() #实例化,维持会话 url_login = 'https://github.com/login' response = session.get(url_login) #通过正则获取token值 authenticity_token = re.findall('name="authenticity_token" value="(.*?)" />',response.text)[0] print(authenticity_token)
当我们获取该参数后,即可以代入form-data中完成登录
import requests import re session = requests.Session() #实例化,维持会话 def token(): url_login = 'https://github.com/login' response = session.get(url_login) #通过正则获取token值 authenticity_token = re.findall('name="authenticity_token" value="(.*?)" />',response.text)[0] return authenticity_token #返回token值 def url_session(token): url = 'https://github.com/session' data = { 'commit': 'Sign in', 'utf8': '✓', 'authenticity_token': token, #authenticity_token参数 'login': '输入账号', #你的账号 'password': '输入密码', #你的密码 'webauthn-support': 'supported', 'required_field_852e': '', 'timestamp': '1565616593723', 'timestamp_secret': '850cb01230466a48f29899e2202265961cdcde8375c4ee69399cd9e9805e1ede', } response = session.post(url,data=data) #传入form-data表单 return response.text #返回源码 def save_github(response_text): with open('github.html','w',encoding='utf-8') as fp: fp.write(response_text) if __name__ == '__main__': token = token() #获取authenticity_token参数 response_text = url_session(token) #获取网页源码 save_github(response_text) #把爬取到的源码保存为html格式
参与评论
手机查看
返回顶部