python爬虫:登录学习猿地
程序员文章站
2022-05-02 22:01:29
...
import re
import requests
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'}
# 登录URL
login_url = 'https://old.lmonkey.com/login'
# 记录登录状态,使用正则获取登录所需的_token
session = requests.Session()
r = session.get(login_url, headers=headers)
_token = re.findall('<meta name="csrf-token" content="(.*?)">', r.text)
# 输入登录所需的用户名和密码
username = input('enter username:')
password = input('enter password:')
# 构建登录的data字典
data = {
'_token': _token,
'username': username,
'password': password,
}
# 登录学习猿地
session.post(login_url, data=data, headers=headers)
# 跳转网站主页
url = 'https://old.lmonkey.com'
r = session.get(url, headers=headers)
# 获取登录后的昵称跟用户名进行对比,确定是否登录成功
nick_name = re.findall("nickName:'(.*?)'", r.text)[0]
if nick_name == username:
print('登录成功!!!!')