本文代码仅供学习交流!
本文用到一个Python的第三方库requests,这个库的简介和安装方法可以参考这里。
本文所用Python版本为2.7,本文选用测试网站为CSDN和51CTO。
一定要注意提交的页面是否正确!
1、CSDN
#encoding=utf-8 import requests from urllib import urlencode headers = { 'Host': 'passport.csdn.net', 'Connection': 'keep-alive', 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded', 'Referer': 'https://passport.csdn.net/account/loginbox?callback=logined&hidethird=1&from=http%3a%2f%2fwww.csdn.net%2f', 'Accept-Encoding': 'gzip,deflate,sdch', 'Accept-Language': 'zh-CN,zh;q=0.8', } username = 'yourusername' password = 'yourpassword' url = 'https://passport.csdn.net/ajax/accounthandler.ashx?t=log&remember=0&f=http%3A%2F%2Fwww.csdn.net%2F&rand=0.8652449736837298' form = urlencode({'u':username.encode('utf-8'), 'p':password.encode('utf-8')}) r = requests.get(url=url, headers=headers, data=form, allow_redirects=True) #通过返回头中是否存在'set-cookie'值判断用户名和密码是否正确 if str(r.headers).lower().find('set-cookie') > -1: print('right') else: print('wrong')
2、51CTO
#coding=utf-8 import requests from urllib import urlencode headers = { 'Host': 'home.51cto.com', 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Origin': 'http://home.51cto.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded', 'Referer': 'http://home.51cto.com/index.php?s=/Index/index/t/1/', 'Accept-Encoding': 'gzip,deflate,sdch', 'Accept-Language': 'zh-CN,zh;q=0.8', } email = 'yourusername' passwd = 'yourpassword' url = 'http://home.51cto.com/index.php?s=/Index/doLogin' form = { 'email':email.encode('utf-8'), 'passwd':passwd.encode('utf-8'), } r = requests.post(url=url, headers=headers, data=form, allow_redirects=False) #通过返回的状态码判断用户名和密码是否正确 if 200 == r.status_code: print('right') else: print('wrong')
3、IE8的User-Agent。
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)
相关阅读:Requests:为人类设计的HTTP库
*** walker ***