#coding:utf-8
import requests
import pickle
import os
class login():
def __init__(self):
print('',end='')
def session(self):
mysession=self.readSession()
print(type(mysession))
return mysession
def getSession(self):
# 通过Session类新建一个会话
session = requests.Session()
post_url = 'http://www.xxx.com/user/login.asp?act=login'
# 往下使用requests的地方,直接使用session即可,session就会保存服务器发送过来的cookie信息
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36',
'Referer':'http://www.xxx.com/user/login.asp?url=http://www.xxx.com/',
'Content-Type':'application/x-www-form-urlencoded',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
}
data = {
'username': 'qq28928247', # 账号
'password': '123456', # 密码
}
print('登录成功')
r = session.post(url=post_url, data=data, headers=headers)
outputPath = open('xxxSession.pickle','wb')
pickle.dump(session,outputPath)
outputPath.close()
return session
def readSession(self):
if os.path.exists('xxxSession.pickle'):
readPath = open('xxxSession.pickle','rb')
tbSession = pickle.load(readPath)
url2 = 'http://www.xxx.com/user/ajax.asp'
headers2= {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36',
'Referer': 'http://www.xxx.com/',
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Content-Type': 'application/x-www-form-urlencoded'
}
data2 = {
'act': 'userpanel',
'url': 'http://www.xxx.com/'
}
r2 = tbSession.post(url=url2,data=data2, headers=headers2)
html2=str(r2.content, 'utf8')
if html2.find('[退出登录]')<0:
tbSession= self.getSession()
else:
tbSession= self.getSession()
return tbSession
调用
login=login()
session=login.session()
url1 = 'http://www.xxx.com/show.asp?id=111'
headers1 = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
}
r = session.get(url=url1, headers=headers1)
if r.status_code==200 :
html1=str(r.content, 'utf8')
print(html1)