#!/usr/bin/python
#-*- coding: utf-8 -*-html
import os,json;
import urllib,urllib2;
import cookielib;python
#獲取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))web
#輸入驗證碼
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("驗證碼錯誤")json
#參考如下資料cookie
http://python.jobbole.com/81344/ui
https://www.cnblogs.com/xiaoxi-3-/p/7586072.htmlurl
http://blog.csdn.net/liuyuan_jq/article/details/69524279spa