知识储备:
1.最常用的HTTP请求方式:get 和post
get:通过URL提交数据,通常参数会显示在地址栏处
post:数据datas放在实体区内提交,通常用在登陆框、提交框等处
2.requests.Session()
一种能自动处理Cookie的方式,不需要关注Cookie的值,每次访问时能自动把Cookie的值带上,类似浏览器
示例:
import requests
#登陆的网址
url='http://xxxxx.com/login'
sess=requests.Session()
#首次访问登陆界面,作为游客,服务器分配一个Cookie
res=sess.get(url)
datas={'name':'xxx','password':'xxxxx'}
#向服务器发送post请求,验证成功,由游客权限转为会员权限
res=sess.post(url,data=datas)
3.Beautiful Soup
一个可以从HTML或XML种提取数据的python的库。
思路流程
首先我们利用浏览器访问github的登陆界面('https://github.com/login'),推荐使用Firefox,点击F12,并点击F5刷新,单击网络可以看到如下get请求,
随便输入一个账号密码后,点击Sign in,出现Post请求(注意观察,此时的post请求对应的网址是‘https://github.com/session’)
单击Post一行,点击右侧参数列,可以看到如下表单参数,这就是我们上面提到的datas,即通过post请求提交的数据
多次输入错误账号或者密码,会发现只有‘authenticity_token’,'login','password'三行参数一直变化,其中后两个是由于我们自己每次输入账号密码不同导致的,问题的关键就是找到‘authenticity_token’所对应的数据。
点击查看器,在搜索html处输入authenticity_token
出现我们要找的‘authenticity_token’所对应的数据
由此可以推测,在每次响应后,服务器都会给出一个authenticity_token对应的数值,作为下一次post请求的表单参数。大家可以进行验证,记录本次响应的authenticity_token值,观察下一次请求所需的authenticity_token值,发现是一致的。
最后就可以通过Session的方法进行模拟登陆了!
实操
1.首先导入必要的库
import requests
import bs4
2.提取authenticity_token值
#登陆网址
url='https://github.com/login'
#创建Session对象
sess=requests.Session()
#初次登陆
re=sess.get(url)
#将复杂HTML文档转化为树形结构,方便提取
soup=bs4.BeautifulSoup(re.content)
#提取authenticity_token值,具体方法这里不多介绍了,结合具体情况具体对待
authenticity_token=soup.find_all('input')[1]['value']
print(authenticity_token)
得到如下结果
3.构建表单数据,datas
data={'commit':'Sign in',
'utf8':'✓',
'authenticity_token':authenticity_token,
#个人账号密码
'login':'[email protected]',
'password':'xxxxxxxxxxxx' ,
'webauthn-support':'unsupported'}
4.模拟登陆
url='https://github.com/session'
sess.post(url,data=data)
5.验证
res=sess.get('https://github.com/yonghuming?tab=stars')
soup=bs4.BeautifulSoup(res.content)
print(soup)
将输出结果复制粘贴到xxx.txt文件内,保存为.html格式,然后双击打开,得到如下(如果出现乱码,将txt编码格式改为‘utf-8’后再保存)
最后附上完整python代码
import requests
import bs4
#登陆网址
url='https://github.com/login'
#创建Session对象
sess=requests.Session()
#初次登陆
re=sess.get(url)
soup=bs4.BeautifulSoup(re.content)
authenticity=soup.find_all('input')[1]['value']
#表单数据
data={'commit':'Sign in',
'utf8':'✓',
'authenticity_token':authenticity,
'login':'[email protected]',
'password':'xxxxx' ,
'webauthn-support':'unsupported'}
#post请求网址
url='https://github.com/session'
sess.post(url,data=data)
#验证
res=sess.get('https://github.com/xxxxx?tab=stars')
soup=bs4.BeautifulSoup(res.content)
print(soup)