首页 > 代码库 > Python 模拟登陆
Python 模拟登陆
import urllib
import urllib.request
import gzip
import http
import http.cookiejar
#定义一个方法用于生成请求头信息,处理cookie
def getOpener(head):
# 初始化一个CookieJar来处理Cookie <pre name="code" class="python">
cj = http.cookiejar.CookieJar()
#实例化一个opener
pro = urllib.request.HTTPCookieProcessor(cj)
opener = urllib.request.build_opener(pro)
header = []
for key, value in head.items():
elem = (key, value)
header.append(elem)
opener.addheaders = header
return opener
def ungzip(data):
#定义一个方法来解压返回信息
try: # 尝试解压
print(‘正在解压.....‘)
data = http://www.mamicode.com/gzip.decompress(data)
print(‘解压完毕!‘)
except:
print(‘未经压缩, 无需解压‘)
return data
#执行操作,就是登陆
# header 这个表示封装成消息头的参数,参数类型是字典
#postDict 这个是用户名和密码的字典参数
def login(header,url,postDict):
opener = getOpener(header)
postData = http://www.mamicode.com/urllib.parse.urlencode(postDict).encode()
op = opener.open(url, postData)
data = http://www.mamicode.com/op.read()
data = http://www.mamicode.com/ungzip(data)
print(data)
if __name__ == ‘__main__‘:
#封装消息头,伪装成浏览器
header = {
‘Host‘: ‘pcpre2.xjuke.com‘,
‘Connection‘: ‘keep-alive‘,
‘Accept-Language‘: ‘zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3‘,
‘Accept‘: ‘application/json, text/plain, */*‘,
‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0‘,
‘Accept-Encoding‘: ‘gzip, deflate‘,
‘Content-Type‘: ‘application/json;charset=utf-8‘,
‘Referer‘: ‘http://pcpre2.xjuke.com/?c=q-5ce/‘,
‘Content-Length‘: ‘58‘
}
#用户名和密码
postDict = {
‘username‘: XXX,
‘password‘: XX,
‘wechatCode‘:‘q-5ce‘
}
login(header,‘XXXXX‘,postDict)
Python 模拟登陆