[Python] Python 模拟登录,并请求
Python 模拟登录,并请求
# encoding: utf-8 import requests import socket import time socket.setdefaulttimeout(10) try: import cookielib except: import http.cookiejar as cookielib class WebLogin(): def __init__(self): # url self.postUrl = 'https://www.***.com/login' self.profileUrl = 'https://www.***.com/profile' # 设置请求头 self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0', 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2', 'Accept-Encoding': 'gzip, deflate,br', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Referer': 'https://www.***.com/login?ref=%2F', 'Host': 'www.***.com', 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Connection': 'keep-alive', 'Content-Length': '60', 'Cache-Control': 'no-cache', } self.headers2 = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0', 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2', 'Accept-Encoding': 'gzip, deflate', 'Referer': 'https://www.***.com/view-2195.html', 'Connection': 'keep-alive', 'Cache-Control': 'no-cache', } # 设置session self.session = requests.Session() # 生成github_cookie文件 self.session.cookies = cookielib.LWPCookieJar(filename='***_cookie') def post_account(self, email, password): post_data = { 'type': 'account', 'captcha': '', 'account': email, 'password': password } response = self.session.post(self.postUrl, data=post_data, headers=self.headers) print(response.text) # exit() # 保存cookies self.session.cookies.save() def load_cookie(self): try: self.session.cookies.load(ignore_discard=True) except: print('cookie 获取不成功') # 判断是否登陆成功 def isLogin(self): try: self.load_cookie() response = self.session.get(self.profileUrl, headers=self.headers2, timeout=10) print(response.text) except requests.exceptions.RequestException as e: print(e) if __name__ == "__main__": WebLogin = WebLogin() WebLogin.post_account(email='***', password='***') WebLogin.isLogin()
本博客地址: wukong1688
本文原文地址:https://www.cnblogs.com/wukong1688/p/11167630.html
转载请著名出处!谢谢~~