使用python模拟网站登录

使用python模拟登录小站,首先你要知道网站登录的细节以及相应的cookie,总的来说三步
获取一个cookie
装载好自己的request
发送请求

下面是代码

#author:liangliang
#email:liangliangyy@gmail.com
#blog:http://www.lylinux.org/
import urllib
import urllib2
import cookielib
import string  
import re 

url = "http://myvpngate.chinacloudapp.cn/htdocs/wp-login.php"

headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36',}  
#这块可以通过抓包工具来获得
postData = {
    'log':'admin',
    'pwd':'password',
    'wp-submit':'登录',
    'redirect_to':'http://myvpngate.chinacloudapp.cn/htdocs/wp-admin/',
    'testcookie':'1'
}

cj = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cookie_support,urllib2.HTTPHandler)
urllib2.install_opener(opener)

h = urllib2.urlopen(url)  

postData = urllib.urlencode(postData)
request = urllib2.Request(url,postData,headers)
print request
response = urllib2.urlopen(request)
text = response.read()
text = unicode(text,'utf-8').encode('gb18030')
print text

发表评论

电子邮件地址不会被公开。 必填项已用*标注