#-*-coding:utf-8 -*-
import urllib2
import urllib
# 验证码登录同步
import cookielib
import damatuWeb
import ssl
from json import loads
from cons import station_name
#证书验证
ssl._create_default_https_context = ssl._create_unverified_context
# 请求验证码图片
c=cookielib.LWPCookieJar()#生成一个储存cookie的对象
cookie=urllib2.HTTPCookieProcessor(c)#绑定
opener=urllib2.build_opener(cookie)
urllib2.install_opener(opener)
# opener绑定,用opener.open请求,自带cookie,实现验证码与登陆同步
city={}
for i in station_name.split("@"):
if not i:
continue
tmp_list=i.split("|")
city[tmp_list[1]]=tmp_list[2]
# print city["长沙"]
# print city["上海"]
from_station=city["长沙"]
to_station=city["上海"]
train_date="2017-11-03"
def getCode():
req=urllib2.Request("https://kyfw.12306.cn/passport/captcha/"
"captcha-image?login_site=E&module="
"login&rand=sjrand&0.3835166812770916")
codeing=opener.open(req).read()#opener
fn=open('code/code.png','wb')
#保存到本地
fn.write(codeing)
fn.close()
def code():
getCode()
req=urllib2.Request('https://kyfw.12306.cn/passport'
'/captcha/captcha-check')
code=damatuWeb.calcCode()
# code=raw_input(">>")
print code
data={
"answer":code,
"login_site":"E",
"rand":"sjrand",
}
data=urllib.urlencode(data)#把字典类型转变为查询字符串
html=opener.open(req,data=data).read()
result=loads(html)
if result["result_code"]=="4":
print"验证码校验成功!"
return True
else:
print "验证码校验失败"
code()
def login():
#登录
req=urllib2.Request('https://kyfw.12306.cn/passport'
'/web/login')
data={
'username':'abcdert',
'password':'123456',
'appid':'otn',
}
data=urllib.urlencode(data)
html=opener.open(req,data=data).read()
result=loads(html)
if result["result_code"]==0:
print"登陆成功"
return True
else:
print"登陆失败"
def getTrain():
req=urllib2.Request("https://kyfw.12306.cn/otn/leftTicket/query?"
"leftTicketDTO.train_date=%s&leftTicketDTO"
".from_station=%s&leftTicketDTO.to_station=%s&"
"purpose_codes=ADULT" %(train_date,from_station,to_station))
html=opener.open(req).read()
result=loads(html)
return result['data']['result']
# code()
# login()
# print getTrain()
for i in getTrain():
tmp_list=i.split("|")
# tmp_list[3]="车次"
# tmp_list[8]="出发时间"
# tmp_list[9]="到达时间"
# tmp_list[26]="无座"
# tmp_list[29]="硬座"
# tmp_list[25]="特等座"
# tmp_list[31]="一等座"
# tmp_list[30]="二等座"
# tmp_list[23]="软卧"
# a=0
# for n in tmp_list:
# print "[%s]%s"%(a,n)
# a+=1
# break
# print tmp_list
if tmp_list[30]!=u"无" and tmp_list[30]!="":
print "有票","车次:",tmp_list[3]
# break
# else:
# print "没票"
#-*- coding:utf-8 -*-
#python版本3.4
import hashlib
# import http.client
# import urllib.request
import urllib
import urllib2
import json
import base64
def md5str(str): #md5加密字符串
m=hashlib.md5(str.encode(encoding = "utf-8"))
return m.hexdigest()
def md5(byte): #md5加密byte
return hashlib.md5(byte).hexdigest()
class DamatuApi():
ID = '51510'
KEY = '966da54dd89c627c12de3dcd47bc50e1'
HOST = 'http://api.dama2.com:7766/app/'
def __init__(self,username,password):
self.username=username
self.password=password
def getSign(self,param=b''):
return (md5(bytes(self.KEY) + bytes(self.username) + param))[:8]
def getPwd(self):
return md5str(self.KEY +md5str(md5str(self.username) + md5str(self.password)))
def post(self,path,params={}):
data = urllib.urlencode(params).encode('utf-8')
url = self.HOST + path
response = urllib2.Request(url,data)
return urllib2.urlopen(response).read()
#查询余额 return 是正数为余额 如果为负数 则为错误码
def getBalance(self):
data={'appID':self.ID,
'user':self.username,
'pwd':dmt.getPwd(),
'sign':dmt.getSign()
}
res = self.post('d2Balance',data)
res = str(res)
jres = json.loads(res)
if jres['ret'] == 0:
return jres['balance']
else:
return jres['ret']
#上传验证码 参数filePath 验证码图片路径 如d:/1.jpg type是类型,查看http://wiki.dama2.com/index.php?n=ApiDoc.Pricedesc return 是答案为成功 如果为负数 则为错误码
def decode(self,filePath,type):
f=open(filePath,'rb')
fdata=f.read()
filedata=base64.b64encode(fdata)
f.close()
data={'appID':self.ID,
'user':self.username,
'pwd':dmt.getPwd(),
'type':type,
'fileDataBase64':filedata,
'sign':dmt.getSign(fdata)
}
res = self.post('d2File',data)
res = str(res)
jres = json.loads(res)
if jres['ret'] == 0:
#注意这个json里面有ret,id,result,cookie,根据自己的需要获取
return(jres['result'])
else:
return jres['ret']
#url地址打码 参数 url地址 type是类型(类型查看http://wiki.dama2.com/index.php?n=ApiDoc.Pricedesc) return 是答案为成功 如果为负数 则为错误码
def decodeUrl(self,url,type):
data={'appID':self.ID,
'user':self.username,
'pwd':dmt.getPwd(),
'type':type,
'url':urllib.quote(url),
'sign':dmt.getSign(url.encode(encoding = "utf-8"))
}
res = self.post('d2Url',data)
res = str(res)
jres = json.loads(res)
if jres['ret'] == 0:
#注意这个json里面有ret,id,result,cookie,根据自己的需要获取
return(jres['result'])
else:
return jres['ret']
#报错 参数id(string类型)由上传打码函数的结果获得 return 0为成功 其他见错误码
def reportError(self,id):
#f=open('0349.bmp','rb')
#fdata=f.read()
#print(md5(fdata))
data={'appID':self.ID,
'user':self.username,
'pwd':dmt.getPwd(),
'id':id,
'sign':dmt.getSign(id.encode(encoding = "utf-8"))
}
res = self.post('d2ReportError',data)
res = str(res)
jres = json.loads(res)
return jres['ret']
#调用类型实例:
#1.实例化类型 参数是打码兔用户账号和密码
dmt=DamatuApi("zyc3x7z","zyc2021174")
#2.调用方法:
# print(dmt.getBalance()) #查询余额
# print(dmt.decode('code/code.png',287)) #上传打码,第二个位验证码类型
# code=(dmt.decode('code/code.png',287)) #上传打码,第二个位验证码类型
# print(dmt.decodeUrl('http://captcha.qq.com/getimage?aid=549000912&r=0.7257105156128585&uin=3056517021',200)) #上传打码
#print(dmt.reportError('894657096')) #上报错误
def calcCode():
code = (dmt.decode('code/code.png', 287))
code=code.replace('|',',')
code=code.split(',')
x_list=code[0::2]
y_list=code[1::2]
s=""
for i in zip(x_list,y_list):
y=int(i[1])-30
s+='%s,%s,'%(i[0],y)
return s[:-1]
# code=calcCode()
# # code=raw_input(">>")
# print code
抓包抓取城市名称url 保存到文件命名为csdn
https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9029
显示结果
有票 车次: G1352
有票 车次: G1322
有票 车次: G1362
有票 车次: G1372
有票 车次: G1502
有票 车次: G1374
有票 车次: G1364
有票 车次: G1376
有票 车次: G2366
有票 车次: G1330