笔记-爬虫-模拟登录github
笔记-模拟登录github
1. 模拟登录github
1.1. 环境准备
安装/升级requests 2.20.0
pip install --upgrade requests
pip show requests
1.2. 分析登录过程及模拟
- 在chome打开github.com/login,按f12,选中network>preserver log(表示持续日志),进入调试模式。
- 找到登录页面:
检查发现login页面输入内容回车后会跳转页面,实际上是由github.com/session页面接收数据并完成登录。
- 构造请求包:
接下来就是构造请求了,包括headers和form data两部分;
头部构造已经很熟悉了,主要是注意不要漏掉一些字段,包括referer,Origin等,实际上在session页面的post头部中要包含有login页面返回的cookie,但Session会自动完成这个过程,所以不需要手动指定了。
字段全一些可以降低被反爬的机率。
form data分为两部分,固定部分无所谓,但有一个字段authenticity_token是由login页面返回,通过正则找到它即可。
- 发送请求,得到应答;
登录成功后会自动重定向到首页,此时已经做到了session 的状态保持。
- 验证登录成功。
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()