模拟登录某网站

一. 先登录, 再获取登录的cookie, 接着以登录的身份登录网站

import requests

data = {
    'username': '616564099@qq.com',
    'password': 'lqz123',
    'captcha': '1234',
    'remember': '1',
    'ref': 'http://www.aa7a.cn/user.php?act=logout',
    'act': 'act_login',
}
# 第一种方式: 手动获取cookies, 在下次发送请求的时候携带cookies
'''
first_response = requests.post('http://www.aa7a.cn/user.php', data=data)
cookie_jar = first_response.cookies

second_response = requests.get("http://www.aa7a.cn/index.php", cookies=cookie_jar)
print('616564099@qq.com' in second_response.text)  # True 登录以后会以登录邮箱名作为首页的用户名, 因此用它来判断是否模拟成功
'''
# 第二种方式: 使用session()方法, 登录以后自动携带cookies
session = requests.session()
session.post('http://www.aa7a.cn/user.php', data=data)
response = session.get("http://www.aa7a.cn/index.php")
print('616564099@qq.com' in response.text)  # True

二. 如果登录的环境很复杂, 校验的手段很难模拟绕过, 那么就手动登录以后, 拿到cookies进行登录即可!!

# 模拟浏览器, 登录博客, 给别人发送评论内容
import requests

headers = {
    'cookie': '这里填你的cookie值',
    'referer': 'https://i.cnblogs.com/',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
}
response = requests.post('https://www.cnblogs.com/linhaifeng/ajax/PostComment/Add.aspx',
                         json={"postId": 6204014, "body": "我打儿", "parentCommentId": 0}, headers=headers)

print(response.status_code)  # 200
response.encoding = response.apparent_encoding
print(response.json())
'''
{
    'isSuccess': True, 
    'message': '<div class="comment_my_posted"><img style="vertical-align:middle" src="//static.cnblogs.com/images/icon_comment.gif"/> <a href="https://home.cnblogs.com/u/1402974/"><b>给你家马桶唱疏通</b></a>:<blockquote class="bq_post_comment"><p>我打儿</p>\n</blockquote></div>', 
    'duration': '63'
}
'''
posted @ 2020-08-01 19:22  给你加马桶唱疏通  阅读(409)  评论(0编辑  收藏  举报