python2 登录带验证码的页面
#!/usr/bin/python
#-*- coding: utf-8 -*-
import os,json;
import urllib,urllib2;
import cookielib;
#获取cookie
#声明一个CookieJar对象实例来保存cookie
cookie = cookielib.CookieJar()
#利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器
handler=urllib2.HTTPCookieProcessor(cookie)
#通过handler来构建opener
opener = urllib2.build_opener(handler)
#此处的open方法同urllib2的urlopen方法,也可以传入request
response = opener.open('web地址')
#agent标识
user_agent = {'User-Agent':'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
#登录
while True:
#获取验证码
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
req_url='验证码地址'
req=urllib2.Request(url=req_url,headers=user_agent)
content=opener.open(req)
imgpath="code.jpg"
picture=content.read()
with open(imgpath,"wb") as fp:
fp.write(picture)
#弹出验证码图片
os.system("%s/%s"%(os.path.abspath('.'),imgpath))
#输入验证码
req_url='登录地址'
code=raw_input("输入验证码:")
if code == '':
print("验证码不能为空")
continue
print(code)
#验证
req_data_dict={'username':'账号','password':'密码','code':code}
req_data=urllib.urlencode(req_data_dict)
req=urllib2.Request(url=req_url,data=req_data,headers=user_agent)
content=opener.open(req)
login=json.loads(content.read())
if int(login[u'ok']) == 1:
print(cookie)
print('登录成功')
break
else:
print(login)
print("验证码错误")
#参考以下资料
http://python.jobbole.com/81344/
https://www.cnblogs.com/xiaoxi-3-/p/7586072.html
http://blog.csdn.net/liuyuan_jq/article/details/69524279