您的位置:首页 > 编程语言 > Python开发

python自动登陆有cookie验证的网站

2015-03-09 10:27 399 查看
python的功能很强大,封装了好多实用的包,今天我们就用python来实现简单的自动登陆某一需要cookie验证的网站(zhihu)

#python3.3.5

import re
import urllib.request
import urllib
import urllib.parse
import html
import http.cookiejar
import string
import time
import threading

coding="UTF-8"

def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read()
page.close()
html=html.decode(coding)
return html

def autologin():

#登录的主页面
hosturl = 'http://www.zhihu.com/'
#post数据接收和处理的页面(我们要向这个页面发送我们构造的Post数据)
posturl = 'http://www.zhihu.com/login' #从数据包中分析出,处理post请求的url

#设置一个cookie处理器,它负责从服务器下载cookie到本地,并且在发送请求时带上本地的cookie
cj = http.cookiejar.LWPCookieJar()
cookie_support = urllib.request.HTTPCookieProcessor(cj)
opener = urllib.request.build_opener(cookie_support, urllib.request.HTTPHandler)
urllib.request.install_opener(opener)

#打开登录主页面(他的目的是从页面下载cookie,这样我们在再送post数据时就有cookie了,否则发送不成功)
h = urllib.request.urlopen(hosturl)
#构造header,可以随便找一个抓包工具分析得出的。
headers = { 'Accept' : 'text/html, application/xhtml+xml, */*' ,
'Pragma' : 'no-cache' ,
'User-Agent' : 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko',
}
#构造Post数据,就是表单填写
postData = {
'email' : 'xxxxxxx', #你的用户名 ,邮箱地址
'password' : 'xxxxxxxxx', #你的密码,此处密码是明文
}

#需要给Post数据编码
postData = urllib.parse.urlencode(postData).encode(coding)

#通过urllib2提供的request方法来向指定Url发送我们构造的数据,并完成登录过程
request = urllib.request.Request(posturl, postData, headers)

response = urllib.request.urlopen(request)
text = response.read()
text = text.decode('utf-8','ignore').encode('utf-8','ignore')
file =open("zhihu.html",'wb')
file.write(text)
file.close()
autologin()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: