Advertisement

python 火车票订票系统(12306)

阅读量:

研究方法,python+虚拟机+https监视工具

作为一个尚未完善的部分,在整个订票流程中占据重要地位的是那些需要手动操作的部分。
具体流程主要分为以下几个步骤:
第一阶段:通过调用函数获取一个随机数以及用于后续登录的信息。
第二阶段:利用该随机值生成认证码,并结合用户密码进行提交。
第三阶段:将生成的随机值、认证码以及用户密码发送出去。
第四阶段:系统将自动处理这些信息并返回相应的确认结果。
第五阶段:通过特定接口获取最新的列车信息数据。
第六阶段:根据获取到的信息生成完整的订单参数并提交系统。
第七阶段:系统会对订单参数进行校验并返回相应的处理结果。
第八阶段:完成订单提交并获取订单编号。
第九阶段:通过指定方法查询订单状态并获取实时更新信息。
第十阶段:根据订单状态返回相应的处理结果或错误提示信息。

因为网络采用了UTF8编码格式的要求,在脚本头必须设置相应的编码方式。

把代码贴上。

复制代码
 # -*- coding: utf-8 -*-

    
  
    
 import pycurl
    
 import StringIO
    
 import ConfigParser
    
 #这只是一个半成品,只是实现了,一个完整的订票过程,对于,如果刷票,自己研究
    
 #简单过程
    
 #   第一、getRandAndCookie() 获得cook 和一个随机数用于登录 
    
 #   第二、getEnterRandCode() 得到登录时的识别码          
    
 #   第三、setuseandpassword(randcode,use,password) 发送随机数、识别码和用户及密码。由于随机数只在内部使用,所以定义成了全局变量,
    
 #   第四、GetTrainList() 得到所有车站列表,'@bjb|北京北|VAP|beijingbei|bjb|0' 其中有中文、拼音、拼音缩写、所一个ID(唯一),其主要是可以,通过上面的列表,找到它的唯一ID,TranCityToId('南昌')
    
 #   第五、GetTrainNumList(date,fromstationid,tostationid,starttime) 得到哪到哪的所在车次,消息格式如下,其中所以,一下车次的的ID:"id":"650000K1060I"
    
 #        {"end_station_name":"北京西","end_time":"16:18","id":"650000K1060I","start_station_name":"深圳","start_time":"10:54","value":"K106"}
    
 #        通过ChangeToTrainNumId('K106')得到车次ID
    
 #   第六、QueryTrain(fromstationid,tostationid,date,stationNum,starttime) 就是点击查询按键,得到是否有能预订,格式如下
    
 #        <span id='id_5700000Z6809'
    
 #              class='base_txtdiv'
    
 #              οnmοuseοver=javascript:onStopHover('5700000Z6809#NCG#BXP')
    
 #              οnmοuseοut='onStopOut()'>Z68</span>,<img src='/otsweb/images/tips/first.gif'>      南昌     <br>    20:12,<img src='/otsweb/images/tips/last.gif'>    北京西    <br>    07:38,11:26,--,--,--,--,10,<font color='#008800'>有</font>,<font color='#008800'>有</font>,--,<font color='#008800'>有</font>,<font color='#008800'>有</font>,--,<a name='btn130_2' class='btn130_2' style='text-decoration:none;'
    
 #              οnclick=javascript:getSelected('Z68#11:26#20:12#5700000Z6809#NCG#BXP#07:38#南昌#北京西#01#04#1*****31804*****00481*****03306*****00103*****0162#4AFCA0360B0B029AB6E00E3DF2231EE95B4CA798E4D91F296D9BF4CF#G1')>预        订</a>
    
 #       通过choiceSubmitNum(stationNum,trainsubmitinfo)提取出getSelected()消息
    
 #   第七、submitRequest(choiceSubmitNum(stationNum,trainsubmitinfo),date,starttime) 就是点击预订按钮
    
 #   第八、getrandCheckCode()得到提交订单的识别码  
    
 #   第十、CheckInMyTicket(info,randcode,peoples)点击提交,如果成功的话,就会返回{"errMsg":"Y"}
    
  
    
 # 出于,网络是UTF8格式,所以,必须# -*- coding: utf-8 -*-,(当然,自己转换也是可以的)
    
 # 出于这一个控制台信息,所以,识别码的图片在脚本同一目录
    
 #得到头信息
    
 # -*- coding: utf-8 -*-
    
  
    
  
    
 import pycurl
    
 import StringIO
    
 import ConfigParser
    
 import Image
    
 import os
    
 import re
    
 import time
    
 import json
    
 import sys
    
 import math
    
 import binascii
    
  
    
  
    
 #这只是一个半成品,只是实现了,一个完整的订票过程,对于,如果刷票,自己研究
    
 #简单过程
    
 #   第一、getRandAndCookie() 获得cook 和一个随机数用于登录 
    
 #   第二、getEnterRandCode() 得到登录时的识别码          
    
 #   第三、setuseandpassword(randcode,use,password) 发送随机数、识别码和用户及密码。由于随机数只在内部使用,所以定义成了全局变量,
    
 #   第四、GetTrainList() 得到所有车站列表,'@bjb|北京北|VAP|beijingbei|bjb|0' 其中有中文、拼音、拼音缩写、所一个ID(唯一),其主要是可以,通过上面的列表,找到它的唯一ID,TranCityToId('南昌')
    
 #   第五、GetTrainNumList(date,fromstationid,tostationid,starttime) 得到哪到哪的所在车次,消息格式如下,其中所以,一下车次的的ID:"id":"650000K1060I"
    
 #        {"end_station_name":"北京西","end_time":"16:18","id":"650000K1060I","start_station_name":"深圳","start_time":"10:54","value":"K106"}
    
 #        通过ChangeToTrainNumId('K106')得到车次ID
    
 #   第六、QueryTrain(fromstationid,tostationid,date,stationNum,starttime) 就是点击查询按键,得到是否有能预订,格式如下
    
 #        <span id='id_5700000Z6809'
    
 #              class='base_txtdiv'
    
 #              οnmοuseοver=javascript:onStopHover('5700000Z6809#NCG#BXP')
    
 #              οnmοuseοut='onStopOut()'>Z68</span>,<img src='/otsweb/images/tips/first.gif'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;南昌&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;20:12,<img src='/otsweb/images/tips/last.gif'>&nbsp;&nbsp;&nbsp;&nbsp;北京西&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;07:38,11:26,--,--,--,--,10,<font color='#008800'>有</font>,<font color='#008800'>有</font>,--,<font color='#008800'>有</font>,<font color='#008800'>有</font>,--,<a name='btn130_2' class='btn130_2' style='text-decoration:none;'
    
 #              οnclick=javascript:getSelected('Z68#11:26#20:12#5700000Z6809#NCG#BXP#07:38#南昌#北京西#01#04#1*****31804*****00481*****03306*****00103*****0162#4AFCA0360B0B029AB6E00E3DF2231EE95B4CA798E4D91F296D9BF4CF#G1')>预&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;订</a>
    
 #       通过choiceSubmitNum(stationNum,trainsubmitinfo)提取出getSelected()消息
    
 #   第七、submitRequest(choiceSubmitNum(stationNum,trainsubmitinfo),date,starttime) 就是点击预订按钮
    
 #   第八、getrandCheckCode()得到提交订单的识别码  
    
 #   第十、CheckInMyTicket(info,randcode,peoples)点击提交,如果成功的话,就会返回{"errMsg":"Y"}
    
  
    
  
    
 # 出于,网络是UTF8格式,所以,必须# -*- coding: utf-8 -*-,(当然,自己转换也是可以的)
    
 # 出于这一个控制台信息,所以,识别码的图片在脚本同一目录
    
 #得到头信息
    
 def headerCookie(buf):
    
     global Cookie
    
    # print buf
    
     findindex  = buf.find("Set-Cookie:")
    
     if findindex >= 0:
    
         beginindex = buf.find(':')
    
         endindex = buf.find(';')
    
         if endindex >0:
    
             Cookie+=buf[beginindex+1:endindex+1]
    
 #用于测试
    
 def gethead(buf):
    
     #
    
     None
    
     #print buf
    
 def setcer(curl):
    
     curl.setopt(pycurl.CAINFO, r"srca.cer") #根证书
    
     None
    
 ##得到随机数和cookie连接参数
    
 def getRandAndCookie():
    
     global loginRand
    
     global Cookie
    
     Cookie = ''
    
     loginRand = ''
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, "https://www.12306.cn/otsweb/loginAction.do?method=loginAysnSuggest")
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write)  
    
     curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    
     curl.setopt(pycurl.HEADERFUNCTION, headerCookie)
    
     #curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.perform()
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         back = b.getvalue()
    
         login = back.find('loginRand')
    
         if login >=0:
    
             begin =login + back[login:].find(':')
    
             begin += back[begin:].find('"')
    
             end =  back[begin+1:].find('"')
    
             loginRand = back[begin+1:end+begin+1]
    
     curl.close()
    
     return loginRand
    
 def getEnterRandCode():
    
     #得到登录验证码图
    
     curl = pycurl.Curl()
    
     f = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/otsweb/passCodeNewAction.do?module=login&rand=sjrand")
    
     #更改了 以前是https://www.12306.cn/otsweb/passCodeAction.do?rand=sjrand")
    
     curl.setopt(pycurl.WRITEFUNCTION, f.write)  
    
     curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    
     curl.setopt(pycurl.HEADERFUNCTION, headerCookie)
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.perform()
    
     backinfo = ''
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = f.getvalue()
    
     curl.close()
    
     return backinfo
    
 def GetKeyhttp():
    
     curl = pycurl.Curl()
    
     f = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/otsweb/loginAction.do?method=init")
    
     curl.setopt(pycurl.WRITEFUNCTION, f.write)  
    
     curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    
     curl.setopt(pycurl.HEADERFUNCTION, gethead)
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.ENCODING, 'gzip, deflate')
    
     curl.setopt(pycurl.HTTPHEADER,["Accept-Language:zh-CN",
    
                                    "Referer:https://dynamic.12306.cn/otsweb/",
    
                                    "Accept:*/*",
    
                                    "Accept-Encoding:gzip, deflate",
    
                                    "Connection:Keep-Alive"])
    
     curl.perform()
    
     backinfo = ''
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = f.getvalue()
    
     curl.close()
    
     begin = backinfo.find('/otsweb/dynamicJsAction.do?jsversion=')
    
     end = backinfo[begin+1:].find('"') + begin+1
    
     return "https://dynamic.12306.cn"+backinfo[begin:end]
    
     #/otsweb/dynamicJsAction.do?jsversion=4296&method=loginJs
    
     
    
     return backinfo
    
     
    
 def GetNewKey():
    
     http = GetKeyhttp()
    
     print http
    
     curl = pycurl.Curl()
    
     f = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, http)
    
     curl.setopt(pycurl.WRITEFUNCTION, f.write)  
    
     curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    
     curl.setopt(pycurl.HEADERFUNCTION, gethead)
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.ENCODING, 'gzip, deflate')
    
     curl.setopt(pycurl.HTTPHEADER,["Accept-Language:zh-CN",
    
                                    "Referer:https://dynamic.12306.cn/otsweb/loginAction.do?method=init",
    
                                    "Accept:*/*",
    
                                    "Accept-Encoding:gzip, deflate",
    
                                    "Connection:Keep-Alive"])
    
     curl.perform()
    
     backinfo = ''
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = f.getvalue()
    
     curl.close()
    
  
    
  
    
     fkey = backinfo.find('function gc()')
    
     if fkey > 0:
    
         beginkey = backinfo[fkey:].find("'") + fkey
    
         end = backinfo[beginkey+1:].find("'") + beginkey+1
    
         return backinfo[beginkey+1:end].replace('=','%3D')+'='+(Get12306NewKey(backinfo[beginkey+1:end]).replace('=','%3D'))
    
 def stringToLongArray(string, includeLength):
    
     length = len(string)
    
     result = []
    
     i = 0;
    
     while (i < length):
    
         re = 0
    
         try:
    
             re = ord(string[i:i+1])
    
             re = re | (ord(string[i+1:i+2] )<< 8)
    
             re = re | (ord(string[i+2:i+3] )<< 16)
    
             re = re | (ord(string[i+3:i+4] )<< 24)
    
         except:
    
             pass
    
         result.append(re)
    
         i += 4
    
     if (includeLength):
    
         result.append(length)
    
     return result
    
 def longArrayToString(data,includeLength):
    
     length = len(data)
    
     n = (length - 1) << 2
    
     if (includeLength):
    
         m = data[length - 1]
    
         if((m < n - 3) or (m > n)):
    
             return None
    
         n = m
    
     bdata = ""
    
     for i in range(0,length):#(var i = 0;i < length;i ++ ):
    
         bdata  = bdata + chr(data[i] & 0xff) + chr(data[i] >> 8 & 0xff) + chr(data[i] >> 16 & 0xff) + chr(data[i] >> 24 & 0xff)
    
     if (includeLength):
    
         return bdata[0:n]
    
     else:
    
         return bdata
    
 def Base32encrypt(string, key):
    
     if (string == ""):
    
         return "";
    
     delta = 0x9E3779B8
    
     v = stringToLongArray(string, True)
    
     k = stringToLongArray(key, False)
    
     k_length = len(k)
    
     if (k_length < 4):
    
         k.append(0)
    
         k.append(0)
    
         k.append(0)
    
         k_length = 4
    
     v_length = len(v)
    
     n = v_length - 1;
    
     z = v[n]
    
     y = v[0];
    
     q = math.floor(6 + 52 / (n + 1))
    
     sum = 0
    
     while (0 < q ):
    
         q = q -1
    
         sum = sum + delta & 0xffffffff;
    
         e = sum >> 2 & 3;
    
         for p in range(0,n):#(p = 0; p < n; p ++ ):
    
             y = v[p + 1];
    
             mx = (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
    
             z = v[p] = v[p] + mx & 0xffffffff;
    
         p = n
    
         y = v[0];
    
         mx = (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
    
         z = v[n] = v[n] + mx & 0xffffffff;
    
     return longArrayToString(v, False);
    
 def encode32(inputbuf):
    
     keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
     #inputbuf = escape(inputbuf);
    
     output = "";
    
     i = 0;
    
     sing = 0
    
     while (i < len(inputbuf)):
    
         chr1 = ord(inputbuf[i:i+1])
    
         i = i + 1
    
         try:
    
             chr2 = ord(inputbuf[i:i+1])
    
             i = i + 1
    
         except:
    
             chr2 = 0
    
             sing = sing or 0x1
    
         try:
    
             chr3 = ord(inputbuf[i:i+1])
    
             i = i + 1
    
         except:
    
             chr3 = 0
    
             sing = sing or 0x2
    
         enc1 = chr1 >> 2;
    
         enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
    
         enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
    
         enc4 = chr3 & 63;
    
         if (sing and 0x1):
    
             enc3 = enc4 = 64
    
         elif (sing and 0x2):
    
             enc4 = 64
    
         output = output + keyStr[enc1:enc1+1] + keyStr[enc2:enc2+1] + keyStr[enc3:enc3+1] + keyStr[enc4:enc4+1]
    
  
    
  
    
     return output
    
 def Get12306NewKey(string):
    
     key = '1111'
    
     string = string
    
     b = Base32encrypt(key,string)
    
     b = binascii.b2a_hex(b)
    
     return  encode32(b)#encode32(b)
    
 #发送用户和密码,即登录
    
 def setuseandpassword(randcode,usename,password,newkey):#nrandcode验证码  usename 用户名 password 密码
    
     data =[]
    
     Crlf = '&'
    
     data.append('loginRand=%s'%(loginRand))
    
     data.append('refundLogin=N')
    
     data.append('refundFlag=Y')
    
     data.append('isClick=&form_tk=null')
    
     data.append('loginUser.user_name=%s'%(usename))
    
     data.append('nameErrorFocus=')
    
     data.append('user.password=%s'%(password))
    
     data.append('passwordErrorFocus=')
    
     data.append('randCode=%s'%(randcode))
    
     data.append('randErrorFocus=')
    
     
    
     data.append(newkey) #这个不知道为什么,不要还能登入
    
     data.append('myversion=undefined')
    
     
    
     senddata = Crlf.join(data)
    
     print senddata
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()#https://dynamic.12306.cn/otsweb/loginAction.do?method=login
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/otsweb/loginAction.do?method=login")
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write)
    
     curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
     curl.setopt(pycurl.HEADERFUNCTION, gethead)
    
     curl.setopt(pycurl.ENCODING, 'gzip, deflate')
    
     curl.setopt(pycurl.HTTPHEADER,["Accept-Language:zh-CN",
    
                                    "Accept-Encoding:gzip, deflate"])
    
     #curl.setopt(pycurl.CAINFO, r"/home/china/桌面/myPython/srca.cer") #根证书
    
     #curl.setopt(pycurl.SSLCERT,"/home/china/桌面/myPython/srca.cer") #客户端证书
    
     #curl.setopt(pycurl.SSLKEY, "/home/china/桌面/myPython/srca.cer") #客户端密钥
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     #curl.setopt(pycurl.HTTPPOST,data)
    
     curl.setopt(pycurl.POSTFIELDS,str(senddata))
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
     curl.close()
    
     return backinfo
    
 #用于分析,登录时返回,用户名的信息
    
 def transitionGetUseInfo(info):
    
     if info == None:
    
         return 'error_ininfo'
    
     if info.find('请输入正确的验证码!') > 0:
    
         return 'error_rand_code'
    
     index = info.find("var hello = '")
    
     if index > 0:
    
         end = index+14+info[index+14:].find("'")
    
         return info[index+13:end]
    
     return 'error_unknow'
    
 #得到火车列表,其中含有名字和ID等相关信息。名字有中、拼、缩写等
    
 def GetTrainList():
    
     global train 
    
     url = 'https://dynamic.12306.cn/otsweb/js/common/station_name.js?version=5.68'
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, url)
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write)  
    
     curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    
     #curl.setopt(pycurl.HEADERFUNCTION, gethead)
    
     try:
    
         curl.setopt(pycurl.COOKIE,Cookie)
    
     except:
    
         None
    
     curl.perform()
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         train = b.getvalue()
    
         curl.close()
    
         return train
    
     curl.close()
    
     return None
    
 #将火车站名转化为ID,拼音、拼音缩写、中文都可以,调用条会是,GetTrainList返回成功
    
 def TranCityToId(stationName):
    
     Id = ""
    
     index =train.find('|'+stationName+'|')
    
     if index < 0:
    
         return None
    
     index = index +1
    
     begin = index-100
    
     if index < 100:
    
         begin = 0
    
     begin = index - train[index:begin:-1].find('@')
    
     if begin ==  -1:
    
         return None
    
     begin = begin+train[begin:].find('|')
    
     if begin ==  -1:
    
         return None
    
     begin = begin+train[begin+1:].find('|')+1
    
     if begin ==  -1:
    
         return None
    
     end = begin+train[begin+1:].find('|')+1
    
     if end ==  -1:
    
         return None
    
     return train[begin+1:end]
    
 #查询列车,批定车次、时间、等 例如:北京到南昌 2013-01-02 L110,车站id是用TranCityToId转化而来的(
    
 def QueryTrain(fromstationid,tostationid,stationtime,stationNum,starttime):#返回的结果,之所以不使用全局变量是因为,这个可以存在多个的。
    
     #stationNum 如果为None那就是所有的车次,stationtime格式:2013-01-02 starttime:00:00--24:00
    
     if fromstationid == None or tostationid == None or stationtime == None:
    
         return
    
     crlf = '&'
    
     httpurl = []
    
     httpurl.append('https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=queryLeftTicket')
    
     httpurl.append('orderRequest.train_date=%s'%(stationtime))#开车日期 2012-12-21
    
     httpurl.append('orderRequest.from_station_telecode=%s'%(fromstationid))#出发站id
    
     httpurl.append('orderRequest.to_station_telecode=%s'%(tostationid))#到站ID
    
     httpurl.append('orderRequest.train_no=%s'%(stationNum))#列车
    
     httpurl.append('trainPassType=%s'%('QB'))#路过类型,全部
    
     httpurl.append(r'trainClass=QB%23D%23Z%23T%23K%23QT%23')#%23 == #QB 全部 D:动车 Z:直达等
    
     httpurl.append('includeStudent=00')#是否是学生,默认为否
    
     httpurl.append('seatTypeAndNum=')#未知
    
     httpurl.append('orderRequest.start_time_str=%s'%(starttime.replace(':','%3A')))
    
     url = crlf.join(httpurl)
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, url)
    
     curl.setopt(pycurl.HTTPHEADER,["x-requested-with:XMLHttpRequest",
    
                                    "Accept:text/plain, */*",
    
                                    "Referer:https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init"])
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write)  
    
     curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    
     curl.setopt(pycurl.HEADERFUNCTION, gethead)
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
     curl.close()
    
     return backinfo
    
 #查询哪到哪的所有车的时间和ID。ID以后要用
    
 def GetTrainNumList(date,fromstationid,tostationid,starttime):#date格式:2013-01-02,starttime 格式:00:00--24:00
    
     global TrainNumList
    
     url = 'https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=queryststrainall'
    
     crlf = '&'
    
     gdata = []
    
     gdata.append('date=%s'%(date))
    
     gdata.append('fromstation=%s'%(fromstationid))
    
     gdata.append('tostation=%s'%(tostationid))
    
     gdata.append('starttime=%s%%3A%s--%s%%3A%s'%(starttime[0:2],starttime[3:5],starttime[7:9],starttime[10:12]))
    
     data = crlf.join(gdata)
    
     
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, url)
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write)  
    
     curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.POSTFIELDS,data)
    
     curl.perform()
    
     TrainNumList = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         TrainNumList = b.getvalue()
    
     curl.close()
    
     return TrainNumList
    
 #通过列车号,转化为唯一ID,必须在GetTrainNumList)成功调用之后
    
 def ChangeToTrainNumId(train_no):
    
     index = TrainNumList.find(train_no)
    
     if index <= -1:
    
         return None
    
     begin = index - TrainNumList[index::-1].find('{')
    
     begin = begin + TrainNumList[begin:].find(r'"id":')
    
     begin = begin + TrainNumList[begin+6:].find(r'"')-6
    
     end = begin + TrainNumList[begin+1:].find(r'"')
    
     return TrainNumList[begin:end+1]
    
 #用于选择,查询后的可预定的车次字符串
    
 def choiceSubmitNum(TrainId,info):
    
     begin = 0
    
     while True:
    
         temp = info[begin:].find('οnclick=javascript:getSelected(')
    
         if temp == -1:
    
             break
    
         begin += temp
    
         begin += info[begin:].find("'")
    
         end =begin+1+ info[begin+1:].find("'")
    
         if info[begin+1:end].find(TrainId) >= 0:
    
             backinfo = info[begin+1:end]
    
             return backinfo
    
     return None
    
 def strtohex(nstr):
    
     tstr = ''
    
     for i in nstr:
    
         tstr+=str(hex(ord(i)))
    
     tstr = tstr.replace('0x','%')
    
     return tstr.upper()
    
 #得到提交定单的令牌,相当于点击预定
    
 def submitRequest(selectStr,train_date ,start_time_str):#返回的结果,之所以不使用全局变量是因为,这个可以存在多个的。
    
     #selectStr 此是点击查询后得到的字符串列表,以#分开的
    
     #train_date 开车日期,例如:2012-12-21
    
     #start_time_str 00:00--24:00'
    
     if selectStr == None:
    
         return None
    
     selectStr_arr = selectStr.split("#")
    
     station_train_code=selectStr_arr[0]#车次
    
     lishi=selectStr_arr[1]#历时
    
     starttime=selectStr_arr[2]#开车时间 
    
     trainno=selectStr_arr[3]#车次编号,唯一
    
     from_station_telecode=selectStr_arr[4]#出发站编号,字符
    
     to_station_telecode=selectStr_arr[5]#到站编号,字符
    
     arrive_time=selectStr_arr[6]#到达时间
    
     from_station_name=selectStr_arr[7]#出发站名字
    
     to_station_name=selectStr_arr[8]#到站名字
    
     from_station_no=selectStr_arr[9]#出发站编号,数字
    
     to_station_no=selectStr_arr[10]#到站编号,数字
    
     ypInfoDetail=selectStr_arr[11]#暂时不知道
    
     mmStr = selectStr_arr[12]#暂时不知道
    
     locationCode = selectStr_arr[13]
    
     lishi = lishi.replace(':','%3A')
    
     starttime = starttime.replace(':','%3A')
    
     arrive_time = arrive_time.replace(':','%3A')
    
     data =[]
    
     Crlf = '&'
    
     data.append('station_train_code=%s'%(station_train_code))
    
     data.append('train_date=%s'%(train_date))#车的日期,年月日 '2013-02-25'
    
     data.append('seattype_num=')#未知
    
     data.append('from_station_telecode=%s'%(from_station_telecode))
    
     data.append('to_station_telecode=%s'%(to_station_telecode))
    
     data.append('include_student=00')#学生与否
    
     data.append('from_station_telecode_name=%s'%(strtohex(from_station_name)))#
    
     data.append('to_station_telecode_name=%s'%(strtohex(to_station_name)))
    
     data.append('round_train_date=%s'%(train_date))#往返日期
    
     data.append('round_start_time_str=%s'%(start_time_str.replace(':','%3A')))#出发时间范围
    
     data.append('single_round_type=%s'%('1'))#是否往返
    
     data.append('train_pass_type=%s'%('QB'))#列车路过的类型
    
     data.append('train_class_arr=%s'%('QB%23D%23Z%23T%23K%23QT%23'))#获取列车类别,为多选框,#号分隔
    
     data.append('start_time_str=%s'%(start_time_str.replace(':','%3A')))
    
     data.append('lishi=%s'%(lishi))#历时时间
    
     data.append('train_start_time=%s'%(starttime))
    
     data.append('trainno4=%s'%(trainno))#列车ID,唯一性的。5700000Z6809
    
     data.append('arrive_time=%s'%(arrive_time))#到站时间
    
     data.append('from_station_name=%s'%(strtohex(from_station_name)))
    
     data.append('to_station_name=%s'%(strtohex(to_station_name)))
    
     data.append('from_station_no=%s'%(from_station_no))
    
     data.append('to_station_no=%s'%(to_station_no))
    
     data.append('ypInfoDetail=%s'%(ypInfoDetail))
    
     data.append('mmStr=%s'%(mmStr))
    
     data.append('locationCode=%s'%(locationCode))
    
     senddata = Crlf.join(data)
    
  
    
  
    
     curl = pycurl.Curl()
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=submutOrderRequest")
    
     curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
     curl.setopt(pycurl.HTTPHEADER,["Referer: https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init",
    
                                    "Content-Type: application/x-www-form-urlencoded"])
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.HEADERFUNCTION, gethead)
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write)
    
     curl.setopt(pycurl.POSTFIELDS,senddata)
    
     curl.perform()
    
     curl.getinfo(pycurl.RESPONSE_CODE)
    
     code = curl.getinfo(pycurl.RESPONSE_CODE)
    
     curl.close()
    
     #print b.getvalue()
    
     if code == 302:
    
         initcurl = pycurl.Curl()
    
         b = StringIO.StringIO()
    
         initcurl.setopt(pycurl.URL, "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init")
    
         initcurl.setopt(pycurl.WRITEFUNCTION, b.write)
    
         initcurl.setopt(pycurl.SSL_VERIFYPEER, False)
    
         initcurl.setopt(pycurl.SSL_VERIFYHOST, False)
    
         initcurl.setopt(pycurl.HTTPHEADER,["Referer:https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init"])
    
         initcurl.setopt(pycurl.COOKIE,Cookie)
    
         initcurl.setopt(pycurl.HEADERFUNCTION, gethead)
    
         initcurl.perform()
    
         #print '2',b.getvalue()
    
         initcurl.close()
    
         return b.getvalue()
    
     return None
    
 #得到提交订单,识别码
    
 def getrandCheckCode():
    
     curl = pycurl.Curl()
    
     f = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/otsweb/passCodeNewAction.do?module=passenger&rand=randp")
    
     #https://www.12306.cn/otsweb/passCodeAction.do?rand=randp")
    
     curl.setopt(pycurl.HTTPHEADER,["Referer:https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init"])
    
     curl.setopt(pycurl.WRITEFUNCTION, f.write)  
    
     curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.HEADERFUNCTION, gethead)
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = f.getvalue()
    
     curl.close()
    
     return backinfo
    
 #从html得到其值,<name='hyy' value='china'>
    
 def getvalue(info,name):
    
     begin = info.find(name)
    
     if begin == -1:
    
         return ''
    
     if cmp(info[begin-6:begin],'name="') != 0:
    
         return ''
    
     begin = begin+info[begin:].find('value="')
    
     end = begin + 7 + info[begin+7:].find('"')
    
     return info[begin+7:end]
    
 def CheckInMyTicket(submitRequestInfo,randCode,peoples):
    
     #submitRequest返回的数据,也可以通过,它来验证,返回数据的正确性 ,如果订单成功就会返回{"errMsg":"Y"}
    
     data =[]
    
     Crlf = '&'
    
     token = getvalue(submitRequestInfo,'org.apache.struts.taglib.html.TOKEN')
    
     if len(token)<=1:
    
         return None
    
     data.append('org.apache.struts.taglib.html.TOKEN=%s'%(token))
    
     data.append('leftTicketStr=%s'%(getvalue(submitRequestInfo,'leftTicketStr')))
    
     data.append('textfield=%s'%(strtohex(getvalue(submitRequestInfo,'textfield'))))
    
     data.append('orderRequest.train_date=%s'%(getvalue(submitRequestInfo,'orderRequest.train_date')))
    
     data.append('orderRequest.train_no=%s'%(getvalue(submitRequestInfo,'orderRequest.train_no')))
    
     data.append('orderRequest.station_train_code=%s'%(getvalue(submitRequestInfo,'orderRequest.station_train_code')))
    
     data.append('orderRequest.from_station_telecode=%s'%(getvalue(submitRequestInfo,'orderRequest.from_station_telecode')))
    
     data.append('orderRequest.to_station_telecode=%s'%(getvalue(submitRequestInfo,'orderRequest.to_station_telecode')))
    
     data.append('orderRequest.seat_type_code=%s'%(getvalue(submitRequestInfo,'orderRequest.seat_type_code')))
    
     data.append('orderRequest.ticket_type_order_num=%s'%(getvalue(submitRequestInfo,'orderRequest.ticket_type_order_num')))
    
     data.append('orderRequest.bed_level_order_num=%s'%(getvalue(submitRequestInfo,'orderRequest.bed_level_order_num')))#
    
     data.append('orderRequest.start_time=%s'%(getvalue(submitRequestInfo,'orderRequest.start_time').replace(':','%3A')))#00%3A40&
    
     data.append('orderRequest.end_time=%s'%(getvalue(submitRequestInfo,'orderRequest.end_time').replace(':','%3A')))#14%3A13&
    
     data.append('orderRequest.from_station_name=%s'%(strtohex(getvalue(submitRequestInfo,'orderRequest.from_station_name'))))#%E5%8D%97%E6%98%8C&
    
     data.append('orderRequest.to_station_name=%s'%(strtohex(getvalue(submitRequestInfo,'orderRequest.to_station_name'))))#%E5%8C%97%E4%BA%AC%E8%A5%BF&
    
     data.append('orderRequest.cancel_flag=%s'%(getvalue(submitRequestInfo,'orderRequest.cancel_flag')))#1&
    
     data.append('orderRequest.id_mode=%s'%(getvalue(submitRequestInfo,'Y')))#Y&
    
     #最多五个人
    
     i = 1
    
     for persion in peoples.values():
    
         data.append('passengerTickets=%s,%s,%s,%s,%s,%s,%s,%s'%(persion['seat'],'0',persion['ticket'],strtohex(persion['name']),persion['cardtype'],persion['idcard'],'','Y'))
    
         data.append('oldPassengers=%s'%(''))#&如果是在常用联系人里就会使用此项
    
         data.append('passenger_%d_seat=%s'%(i,persion['seat']))#1 硬座 3 硬卧 4 软卧
    
         data.append('passenger_%d_ticket=%s'%(i,persion['ticket']))#1&成人票,2 儿童票 3 学生票 4 残军票
    
         data.append('passenger_%d_name=%s'%(i,strtohex(persion['name'])))#
    
         data.append('passenger_%d_cardtype=%s'%(i,persion['cardtype']))#1 二代身份证 2 一代身份证  c 港澳通行证 G 台湾通行证 B 护照
    
         data.append('passenger_%d_cardno=%s'%(i,persion['idcard']))#& ID
    
         data.append('passenger_%d_mobileno=%s'%(i,persion['mobileno']))#电话号
    
         #data.append('checkbox9=%s'%('Y'))#是否保存在学用联系人,默认是不加入
    
         i+=1
    
     while i <= 5:
    
         data.append('oldPassengers=%s'%(''))#&
    
         #data.append('checkbox9=%s'%('Y'))#Y&
    
         i+=1
    
     data.append('randCode=%s'%(randCode))#=ze9q&
    
     data.append('orderRequest.reserve_flag=%s'%(getvalue(submitRequestInfo,'orderRequest.reserve_flag')))#=A&
    
     sendcheckdata =  Crlf.join(data)
    
     data.append('tFlag=%s'%('dc'))#=dc submit_form_confirm('confirmPassenger','dc')
    
     
    
     senddata = Crlf.join(data)
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write)
    
     #用于查询是否有票或及排队情况
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=checkOrderInfo&rand=%s"%(randCode))
    
     curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
     curl.setopt(pycurl.HTTPHEADER,["x-requested-with:XMLHttpRequest",
    
                                    "Content-Type:application/x-www-form-urlencoded",
    
                                    "Referer:https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init#"])
    
    
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.HEADERFUNCTION, gethead)
    
     curl.setopt(pycurl.POSTFIELDS,senddata)
    
     time.sleep(0.2)
    
     curl.perform()
    
     backinfo = ""
    
     print "f",b.getvalue()
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
         curl.close()
    
         time.sleep(0.2)#这个提交的不能太快,应该是12306防快提交
    
         curl = pycurl.Curl()
    
         b = StringIO.StringIO()
    
         curl.setopt(pycurl.WRITEFUNCTION, b.write)
    
         httpdata = []
    
         #得到结果,如果有足够的票就返回{"checkHuimd":"Y","check608":"Y","msg":"","errMsg":"Y"}
    
         httpdata.append("https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=getQueueCount")
    
         httpdata.append("train_date=%s"%(getvalue(submitRequestInfo,'orderRequest.train_date')))
    
         httpdata.append("train_no=%s"%(getvalue(submitRequestInfo,'orderRequest.train_no')))
    
         httpdata.append("station=%s"%(getvalue(submitRequestInfo,'orderRequest.station_train_code')))
    
         httpdata.append("seat=%s"%(persion['seat']))
    
         httpdata.append("from=%s"%(getvalue(submitRequestInfo,'orderRequest.from_station_telecode')))
    
         httpdata.append("to=%s"%(getvalue(submitRequestInfo,'orderRequest.to_station_telecode')))
    
         httpdata.append("ticket=%s"%(getvalue(submitRequestInfo,'leftTicketStr')))
    
         curl.setopt(pycurl.URL, Crlf.join(httpdata))
    
         curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
         curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
         curl.setopt(pycurl.HTTPHEADER,["x-requested-with:XMLHttpRequest",
    
                                        "Content-Type:application/x-www-form-urlencoded",
    
                                        "Referer:https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init#"])
    
        
    
         curl.setopt(pycurl.COOKIE,Cookie)
    
         curl.setopt(pycurl.HEADERFUNCTION, gethead)
    
         curl.perform()
    
         backinfo = b.getvalue()
    
         print 's',b.getvalue()
    
         if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
             curl.close()
    
             time.sleep(1)#这个提交的不能太快,应该是12306防快提交
    
             curl = pycurl.Curl()
    
             b = StringIO.StringIO()
    
             curl.setopt(pycurl.WRITEFUNCTION, b.write) 
    
             curl.setopt(pycurl.URL, "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=confirmSingleForQueue")
    
             curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
             curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
             curl.setopt(pycurl.HTTPHEADER,["x-requested-with:XMLHttpRequest",
    
                                            "Content-Type:application/x-www-form-urlencoded",
    
                                            "Referer:https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init#"])
    
             curl.setopt(pycurl.COOKIE,Cookie)
    
             curl.setopt(pycurl.HEADERFUNCTION, gethead)
    
             curl.setopt(pycurl.POSTFIELDS,sendcheckdata)
    
             curl.perform()
    
             backinfo = b.getvalue()
    
     curl.close()
    
     return backinfo
    
 def GetMyPeople():#得到学用联系人
    
     url = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=getpassengerJson"
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, url)
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write)  
    
     curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.POSTFIELDS,'')
    
     curl.perform()
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         train = b.getvalue()
    
         curl.close()
    
         return train
    
     curl.close()
    
     return None
    
 def QueryUnfinishedTicket():#查询未完成的订单
    
     url = "https://dynamic.12306.cn/otsweb/order/myOrderAction.do?method=queryMyOrderNotComplete&leftmenu=Y"
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, url)
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write)  
    
     curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    
     curl.setopt(pycurl.HTTPHEADER,["Referer:https://dynamic.12306.cn/otsweb/loginAction.do?method=login"])
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.POSTFIELDS,'')
    
     curl.perform()
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         ticket = b.getvalue()
    
         curl.close()
    
         return ticket
    
     curl.close()
    
     return None
    
 def WaitQueryCheckOutInfo():#得到提交订单的结果
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write) 
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/otsweb/order/myOrderAction.do?method=queryOrderWaitTime&tourFlag=dc")
    
     curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
     curl.setopt(pycurl.HTTPHEADER,["x-requested-with:XMLHttpRequest",
    
                                     "Content-Type:application/x-www-form-urlencoded",
    
                                     "Referer:https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init"])
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
     curl.close()
    
     return backinfo
    
 def writefile_map(name,data):
    
     files = open(name,'wb')
    
     files.write(data)
    
     files.close()
    
     
    
     try:
    
         os.startfile(name)
    
     except:
    
         im = Image.open(name)
    
         im.show()
    
     #os.startfile(name)
    
 def ReadConfig():
    
     try:
    
      config = ConfigParser.ConfigParser()
    
      config.readfp(open('/home/china/桌面/myPython/cookie.ini',"rb"))
    
      return config.get("Myini","cookie")
    
     except:
    
         return ''
    
 def WriteConfig(nCookie):
    
     config = ConfigParser.ConfigParser()
    
     config.set("Myini","cookie",nCookie)
    
     cf.write(open("/home/china/桌面/myPython/cookie.ini", "w"))
    
 def FlashAllTrainListCode():
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write) 
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/TrainQuery/passCodeActi0n.do?rand=rrand?0.38251218537598275")
    
     curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
     curl.setopt(pycurl.HTTPHEADER,["Referer:http://dynamic.12306.cn/TrainQuery/trainPassStationByTrainCode.jsp"])
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.HEADERFUNCTION, headerCookie)
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
     curl.close()
    
     return backinfo
    
 def GetAllTrainListCode():
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write) 
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/TrainQuery/passCodeActi0n.do?rand=rrand")
    
     curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
     curl.setopt(pycurl.HTTPHEADER,["Referer:http://dynamic.12306.cn/TrainQuery/trainPassStationByTrainCode.jsp"])
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.HEADERFUNCTION, headerCookie)
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
     curl.close()
    
     return backinfo
    
 def GetAllTrainListStationtoStationAndTrain(nmonth,nday,train,rand,startStation,arriveStation):
    
     #condition=&nmonth2=08&nmonth2_new_value=true&
    
     #nday2=08&nday2_new_value=false&
    
     #startStation_ticketPrice1=%E5%8C%97%E4%BA%AC&
    
     #startStation_ticketPrice1_new_value=false&
    
     #arriveStation_ticketPrice1=%E5%8D%97%E6%98%8C&
    
     #arriveStation_ticketPrice1_new_value=false&
    
     #trainCode=Z65&
    
     #trainCode_new_value=false&rFlag=1&name_ckball=value_ckball&tFlagDC=DC&tFlagZ=Z&tFlagT=T&tFlagK=K&tFlagPK=PK&tFlagPKE=PKE&tFlagLK=LK&randCode=1
    
  
    
  
    
     data =[]
    
     Crlf = '&'
    
     data.append('condition=')
    
     data.append('nmonth2=%s'%(nmonth))
    
     data.append('nmonth2_new_value=true')
    
     data.append('nday2=%s'%(nday))
    
     data.append('nday2_new_value=false')
    
     data.append('startStation_ticketPrice1=%s'%(startStation))
    
     data.append('startStation_ticketPrice1_new_value=false')
    
     data.append('arriveStation_ticketPrice1=%s'%(arriveStation))
    
     data.append('arriveStation_ticketPrice1_new_value=false')
    
     data.append('trainCode=%s'%(train))
    
     data.append('trainCode_new_value=false&rFlag=1&name_ckball=value_ckball&tFlagDC=DC&tFlagZ=Z&tFlagT=T&tFlagK=K&tFlagPK=PK&tFlagPKE=PKE&tFlagLK=LK')
    
     data.append('randCode=%s'%(rand))
    
     senddata = Crlf.join(data)
    
     #print senddata
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write) 
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/TrainQuery/iframeTicketPriceByStation.jsp")
    
     curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
     curl.setopt(pycurl.HTTPHEADER,["Referer:http://dynamic.12306.cn/TrainQuery/ticketPriceByStation.jsp"])
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.POSTFIELDS,senddata)
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
     curl.close()
    
     return backinfo
    
 def GetAllTrainListStationtoStation(nmonth,nday,rand,startStation,arriveStation):
    
     #nmonth1=08&
    
     #nmonth1_new_value=true&
    
     #nday1=08&
    
     #nday1_new_value=false&
    
     #startStation=%E5%8D%97%E6%98%8C&
    
     #startStation_new_value=false&
    
     #arriveStation=%E5%8C%97%E4%BA%AC&
    
     #arriveStation_new_value=false&rFlag=1&name_ckball=value_ckball&tFlagDC=DC&tFlagZ=Z&tFlagT=T&tFlagK=K&tFlagPK=PK&tFlagPKE=PKE&tFlagLK=LK&randCode=5
    
  
    
  
    
     data =[]
    
     Crlf = '&'
    
     data.append('nmonth1=%s'%(nmonth))
    
     data.append('nmonth1_new_value=true')
    
     data.append('nday1=%s'%(nday))
    
     data.append('nmonth1_new_value=false')
    
     data.append('startStation=%s'%(startStation))
    
     data.append('trainCode1_new_value=false')
    
     data.append('arriveStation=%s'%(arriveStation))
    
     data.append('arriveStation_new_value=false&rFlag=1&name_ckball=value_ckball&tFlagDC=DC&tFlagZ=Z&tFlagT=T&tFlagK=K&tFlagPK=PK&tFlagPKE=PKE&tFlagLK=LK')
    
     data.append('randCode=%s'%(rand))
    
     senddata = Crlf.join(data)
    
     #print senddata
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write) 
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/TrainQuery/iframeTrainInfoByStation.jsp")
    
     curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
     curl.setopt(pycurl.HTTPHEADER,["Referer:http://dynamic.12306.cn/TrainQuery/trainInfoByStation.jsp"])
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.POSTFIELDS,senddata)
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
     curl.close()
    
     return backinfo
    
 def GetAllTrainList(nmonth,nday,trainCode,rand):
    
     #nmonth1=03&nmonth1_new_value=false&nday1=13&nday1_new_value=false&trainCode1=Z68&trainCode1_new_value=true&randCode=9
    
     data =[]
    
     Crlf = '&'
    
     data.append('nmonth1=%s'%(nmonth))
    
     data.append('nmonth1_new_value=false')
    
     data.append('nday1=%s'%(nday))
    
     data.append('nmonth1_new_value=false')
    
     data.append('trainCode1=%s'%(trainCode))
    
     data.append('trainCode1_new_value=true')
    
     data.append('startStation_ticketPrice1=保定')
    
     data.append('randCode=%s'%(rand))
    
     senddata = Crlf.join(data)
    
     #print senddata
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write) 
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/TrainQuery/iframeTrainPassStationByTrainCode.jsp")
    
     curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
     curl.setopt(pycurl.HTTPHEADER,["Referer:http://dynamic.12306.cn/TrainQuery/trainPassStationByTrainCode.jsp"])
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.POSTFIELDS,senddata)
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
     curl.close()
    
     return backinfo
    
 #TrainNumStr T15 ,date 2012-12-21
    
 def GetStationFromTrainNumStr(TrainNumStr,ndate):
    
     data =[]
    
     Crlf = '&'
    
     data.append('method=getTrainName')
    
     data.append('inputValue='+TrainNumStr)
    
     data.append('date='+ndate.replace("-",""))
    
     senddata = Crlf.join(data)
    
     print senddata
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write) 
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/TrainQuery/autocomplete.do")
    
     curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
     curl.setopt(pycurl.HTTPHEADER,["Referer:http://dynamic.12306.cn/TrainQuery/trainPassStationByTrainCode.jsp",
    
                                    "x-requested-with: XMLHttpRequest"])
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.POSTFIELDS,senddata)
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
     curl.close()
    
     return backinfo
    
 def GetTrainAllListFromStationAndTimeAndTrainNum(train_no,from_station_telecode,to_station_telecode,depart_date):
    
     if(train_no == None or from_station_telecode == None or to_station_telecode == None or  depart_date == None):
    
         return ""
    
     crlf = '&'
    
     httpurl = []
    
     httpurl.append('https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=queryaTrainStopTimeByTrainNo')
    
     httpurl.append('train_no='+train_no)
    
     httpurl.append('from_station_telecode='+from_station_telecode)
    
     httpurl.append('to_station_telecode='+to_station_telecode)
    
     httpurl.append('depart_date='+depart_date)
    
     
    
     url = crlf.join(httpurl)
    
     
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, url)
    
     curl.setopt(pycurl.HTTPHEADER,["x-requested-with: XMLHttpRequest",
    
                                    "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init"])
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write)  
    
     curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
     curl.close()
    
     return backinfo
    
 def ChangeStationFromTrainNumStrRe(info):
    
     if info == None:
    
         return None
    
     com = r'''parent.mygrid.addRow\(\d+,"\d+,(.*?)\^.*?self,(\d\d:\d\d),(\d\d:\d\d),(\d\d:\d\d),.*?,.*?\^self,.*?,.*?,(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)"'''#
    
     backinfo = {}
    
     p = re.compile(com,re.DOTALL)
    
     for m in p.finditer(info):
    
         #print m.group(1),m.group(2),m.group(3),m.group(4),m.group(5),m.group(6),m.group(7),m.group(8),m.group(9),m.group(10),m.group(11),m.group(12),m.group(13)
    
         if len(m.group(1))>1:
    
             backinfo[m.group(1)]=[m.group(5),m.group(6),m.group(7),m.group(8),m.group(9),m.group(10),m.group(11),m.group(12),m.group(13)];
    
     if len(backinfo) == 0:
    
         return None
    
     print backinfo
    
  
    
  
    
 def GetTrainAllListFromStationAndTimeAndTrainNumRe(info):
    
     if info == None:
    
         return None
    
     com = r'''parent.mygrid.addRow\(\d+,"\d+,(.*?)\^.*?self,.*?self,(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(\d\d:\d\d),(\d\d:\d\d),(\d\d:\d\d).*?"'''
    
     backinfo = {}
    
     p = re.compile(com,re.DOTALL)
    
     for m in p.finditer(info):
    
         #print m.group(1),m.group(2),m.group(3),m.group(4),m.group(5),m.group(6),m.group(7),m.group(8),m.group(9),m.group(10),m.group(11),m.group(12),m.group(13)
    
         if len(m.group(1))>1:
    
             backinfo[m.group(1)]=[m.group(11),m.group(12),m.group(13),m.group(2),m.group(3),m.group(4),m.group(5),m.group(6),m.group(7),m.group(8),m.group(9),m.group(10)];
    
     if len(backinfo) == 0:
    
         return None
    
     return backinfo
    
 def ChangeStationFromTrainNumStr(statin):
    
     com = r'''<option.*?value='(.*?)_(.*?)'>.*?\((.*?)→(.*?)\).*?</option>'''#
    
     backinfo = []
    
     p = re.compile(com,re.DOTALL)
    
     for m in p.finditer(statin):
    
         listinfo = [m.group(1),m.group(2),m.group(3),m.group(4)]
    
         backinfo.append(listinfo)
    
     return backinfo
    
 def GetInfoFromTrainNum():
    
     statin = 'T145'
    
     date = '2013-03-14'
    
     getRandAndCookie()
    
     GetAllTrainListCode()
    
     info =  GetStationFromTrainNumStr(statin,date)
    
     infolist = ChangeStationFromTrainNumStr(info)
    
     print info.decode("utf-8")
    
     GetTrainList()
    
     for i in infolist:
    
         print GetTrainAllListFromStationAndTimeAndTrainNum(i[1],TranCityToId(i[2]),TranCityToId(i[3]),date)
    
 def GetAllTrainNameList():
    
     TrainNameList = []
    
     try:
    
         tfile = open('traininfo.txt','r')
    
         buf = tfile.readline()
    
         while buf:
    
             be = buf.find(';')
    
             if be > 0:
    
                 en = buf[be+1:].find(';')
    
                 if en > 0:
    
                     TrainNameList.append(buf[be+1:en+be+1])
    
             buf = tfile.readline()
    
         tfile.close()
    
     except:
    
         return None
    
     return TrainNameList
    
 def GetTrainPriceInfo(info):
    
     if info == None or len(info) < 100:
    
         return None
    
     com = '''innerHTML="(<.*?>(.+?)</.*?>.*?((.*?)).*?<.*?>(.+?)</.*?>.*?<.*?>(.+?)</.*?>.*?<.*?>(.+?)</.*?>.*?)"'''#
    
     backinfo = [[],{}]
    
     p = re.compile(com,re.DOTALL)
    
     for m in p.finditer(info):
    
         #print m.group(2),m.group(3).decode("UTF-8"),m.group(4).decode("UTF-8"),m.group(5).decode("UTF-8"),m.group(6)
    
         listinfo = [m.group(2),m.group(3),m.group(4),m.group(5),m.group(6)]
    
         backinfo[0] = listinfo
    
         break
    
  
    
  
    
     if(len(backinfo[0]) == 0):
    
         return None
    
     com = '''parent.mygrid.addRow\ (.*?"(.*?),(.*?)\ ^.*?,.*?,(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)"'''
    
     listinfo = {}
    
     p = re.compile(com,re.DOTALL)
    
     for m in p.finditer(info):
    
         #print m.group(1),m.group(2).decode("UTF-8"),m.group(3),m.group(4),m.group(5),m.group(6),m.group(7),m.group(8),m.group(9),m.group(10),m.group(11),m.group(12),m.group(13),m.group(14)
    
         listinfo[m.group(1)] = [m.group(2),m.group(3),m.group(4),m.group(5),m.group(6),m.group(7),m.group(8),m.group(9),m.group(10),m.group(11),m.group(12),m.group(13),m.group(14)]
    
     backinfo[1] = listinfo
    
     return backinfo
    
 def savePrice(priceListFile,infolist):
    
     for sinfolist in infolist[0]:
    
         priceListFile.write(sinfolist)
    
         priceListFile.write(';')
    
     for i in range(1,len(infolist)):
    
         jsoninfo =  json.dumps(infolist[i], encoding="UTF-8", ensure_ascii=False)
    
         priceListFile.write(jsoninfo.encode('UTF-8'))
    
     priceListFile.write('\n')
    
 def GetQuery(TrainNameList):#查询 车次及价格
    
     if TrainNameList == None:
    
         print 'can find TrainNameList'
    
         return None
    
     backinfo = []
    
     date = time.strftime("%Y-%m-%d",)
    
     nmonth = '%02d'%(time.localtime(time.time()).tm_mon)
    
     nday = '%02d'%(time.localtime(time.time()).tm_mday)
    
     trainCode = "K106"
    
     j = 0
    
     
    
     
    
     getRandAndCookie()
    
     print 'alltrainNum:',len(TrainNameList)
    
     #codemap = GetAllTrainListCode()
    
     #writefile_map('codein.png',codemap)
    
     #randcode = raw_input('imput code:')
    
     try:
    
         priceListFile = open('trainproce.txt','r')
    
         buf = priceListFile.readline()
    
         while buf:
    
             liinfo = [[],{}]
    
             if len(buf)>20:
    
                 f = buf.find('{')
    
                 if f < 0:
    
                     break
    
                 liinfo[0] = buf[0:f-1].split(';')
    
                 liinfo[1] = eval(buf[f:])
    
                 backinfo.append(liinfo)
    
             buf = priceListFile.readline()
    
         priceListFile.close()
    
     except:
    
        pass
    
     print len(backinfo)
    
  
    
  
    
     priceListFile = open('trainproce.txt','w')
    
     j = 0
    
     for bprict in backinfo:
    
         j = j +1
    
         savePrice(priceListFile,bprict)
    
  
    
  
    
     '''for trainCode in TrainNameList:
    
         for bprict in backinfo:
    
             if trainCode == bprict[0][0]:
    
                 trainCode = None
    
                 break
    
         if None == trainCode:
    
             continue
    
         codemap = GetAllTrainListCode()
    
         infolist = None
    
         print trainCode,
    
         for i in range(0,10):
    
             
    
             info = GetAllTrainList(nmonth,nday,trainCode,i)
    
             infolist = GetTrainPriceInfo(info)
    
             if infolist != None:#已查到
    
                 savePrice(priceListFile,infolist)
    
                 j = j +1
    
                 backinfo.append(infolist)
    
                 break
    
         if infolist == None:
    
             print 'error',j
    
         else:
    
             print 'ok',j'''
    
         #randcode = raw_input('imput code:')
    
     priceListFile.close()
    
     priceListFiles = open('trainproce_a_t.txt','a')
    
     nowbacklen = len(backinfo)
    
     for cc in range(0,nowbacklen):
    
         print cc
    
         subinfo = backinfo[cc]
    
         infoRe = None
    
         ssubinfo = subinfo[0]
    
         for j in range(1,len(ssubinfo[1])+1):
    
             subbackinfo = {}
    
             for k in range(j+1,len(ssubinfo[1])+1):
    
                 codemap = GetAllTrainListCode()
    
                 print ssubinfo[0],subinfo[1]['%d'%(j)][0].decode('utf-8'),subinfo[1]['%d'%(k)][0].decode('utf-8'),
    
                 for i in range(0,10):
    
                     #json.dumps(infolist[1], encoding="UTF-8", ensure_ascii=False)
    
                     
    
                     infoRe = GetTrainAllListFromStationAndTimeAndTrainNumRe(
    
                         GetAllTrainListStationtoStationAndTrain(nmonth,nday,ssubinfo[0],i,subinfo[1]['%d'%(j)][0],subinfo[1]['%d'%(k)][0]))
    
                    # print 'y',infoRe == None,infoRe
    
                     
    
                     if infoRe != None:
    
                         print 'h',infoRe
    
                         break
    
                 if infoRe == None:
    
                     print 'error'
    
                 else:
    
                     intoinfo = [subinfo[1]['%d'%(k)][0]]
    
                     for t in infoRe[ssubinfo[0]]:
    
                         intoinfo.append(t)
    
                     #print intoinfo
    
                     
    
                     subbackinfo['%d'%(k-j)] = intoinfo
    
                     priceListFiles.write(ssubinfo[0])#车次
    
                     priceListFiles.write(';')
    
                     #jsoninfo =  json.dumps(intoinfo, encoding="UTF-8", ensure_ascii=False)
    
                     priceListFiles.write(str(intoinfo).encode('UTF-8'))
    
                     priceListFiles.write('\n')
    
                     print 'ok'
    
                     break
    
             if len(subbackinfo)>0:
    
                 backinfo.append([[subinfo[0],subinfo[1],subbackinfo['1'],subbackinfo['%d'%(len(subbackinfo)-1)],len(subbackinfo)],
    
                                  subbackinfo])
    
                 #print backinfo[cc]
    
         print len(backinfo)
    
         #break
    
     priceListFiles.close()
    
     priceListFile = open('trainproce_a.txt','w')
    
     j = 0
    
     for bprict in backinfo:
    
         j = j +1
    
         savePrice(priceListFile,bprict)
    
  
    
  
    
     priceListFile.close()
    
     return backinfo
    
  
    
  
    
  
    
  
    
 def GetTicket(use,password,fromcity,tocity,date,stationName,Peoples):
    
     getRandAndCookie()
    
     codemap = getEnterRandCode()
    
  
    
  
    
     writefile_map('codein.png',codemap)
    
     randcode = raw_input('imput code:')
    
     
    
     newkey = GetNewKey()
    
     print newkey
    
     
    
     #getRandCode()
    
  
    
  
    
     info = setuseandpassword(randcode,use,password,newkey)
    
     #print info
    
     backinfo = transitionGetUseInfo(info)
    
     if backinfo.find('error') >=0:#也就是没有错误时
    
         print backinfo
    
         return None
    
     print "提示:",backinfo.decode("UTF-8")
    
     backinfo = GetTrainList()
    
     if backinfo == None:
    
         return None
    
     fromstationid = TranCityToId(fromcity)
    
     tostationid = TranCityToId(tocity)
    
     if fromstationid == None:
    
         print '出发站未找到'
    
         return None
    
     if tostationid == None:
    
         print '到站未找到'
    
         return None
    
     starttime = '00:00--24:00'
    
     isstudent = False
    
     seatType = ''
    
     backinfo = GetTrainNumList(date,fromstationid,tostationid,starttime)
    
     print backinfo
    
     if backinfo == None:
    
         print 'GetTrainNumList 错误'
    
         return None
    
     print stationName
    
     stationNum = ChangeToTrainNumId(stationName)
    
     if stationNum == None:
    
         print 'ChangeToTrainNumId error'
    
         return None
    
     trainsubmitinfo = QueryTrain(fromstationid,tostationid,date,stationNum,starttime)
    
     #print trainsubmitinfo
    
     if trainsubmitinfo == None:
    
         print 'QueryTrain error'
    
         return None
    
     info = submitRequest(choiceSubmitNum(stationNum,trainsubmitinfo),date,starttime)
    
     #print info
    
     if info == None:
    
         print 'submitRequest error'
    
         return None
    
     codemap = getrandCheckCode()
    
     if len(codemap)<=0:
    
         print 'getrandCheckCode error'
    
         return None
    
     writefile_map('checkout.png',codemap)
    
     
    
     randcode = raw_input('imput code:')
    
     return CheckInMyTicket(info,randcode,Peoples)
    
     #print GetMyPeople()
    
 def RistTrain():#从12306得到数据库
    
     statin = 'T145'
    
     date = time.strftime("%Y-%m-%d",time.localtime(time.time()))
    
     print date
    
     getRandAndCookie()
    
     GetAllTrainListCode()
    
     GetTrainList()
    
     f = open("info.txt","w")
    
     for i in range(0,9999):
    
         statin = "%s"%(i)#raw_input('imput code:')
    
         info =  GetStationFromTrainNumStr(statin,date)
    
         f.write(info)
    
         infolist = ChangeStationFromTrainNumStr(info)
    
         print info.decode("utf-8")
    
     for i in range(0,9999):
    
         statin = "G%s"%(i)#raw_input('imput code:')
    
         info =  GetStationFromTrainNumStr(statin,date)
    
         f.write(info)
    
         infolist = ChangeStationFromTrainNumStr(info)
    
         print info.decode("utf-8")
    
     f.close()
    
     f = open("info.txt","r")
    
     allinfo = {}
    
     line  = f.readline()
    
     num = 0
    
     while line:
    
         infolist = ChangeStationFromTrainNumStr(line)
    
         for i in infolist:
    
             print '1',num,i[1]
    
             allinfo[i[1]] = i[0]+';'+i[2]+';'+i[3]
    
             num = num +1
    
         line = f.readline()
    
     f.close()
    
     num = 0
    
     w = open('train.txt','w')
    
     for subinfo in allinfo.keys():
    
         print num,'2',subinfo,allinfo[subinfo]
    
         num = num+1
    
         w.write(subinfo)
    
         w.write(';')
    
         w.write(allinfo[subinfo])
    
         w.write('\n')
    
     w.close()
    
     q = open('traininfo.txt','w')
    
     sp = ';'
    
     num = 0
    
     for subinfo in allinfo.keys():
    
         print num,'3',allinfo[subinfo]
    
         num =  num +1
    
         si = allinfo[subinfo].split(';')
    
         ginfo = GetTrainAllListFromStationAndTimeAndTrainNum(subinfo,TranCityToId(si[1]),TranCityToId(si[2]),date)
    
         q.write(subinfo)
    
         q.write(';')
    
         q.write(allinfo[subinfo])
    
         q.write(';')
    
         if ginfo.find('<')< 0:
    
             q.write(ginfo)
    
         q.write('\n')
    
     q.close()
    
     os.remove('train.txt')
    
     os.remove('info.txt')
    
 def GetProvince():
    
     url = 'https://dynamic.12306.cn/TrainQuery/sellTicketStation.jsp'
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, url)
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write)
    
     curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
     curl.close()
    
     begin = backinfo.find('p.addOption(')
    
     end =  backinfo[begin:].find(''']]);'''
    
 )+begin+2
    
     return backinfo[begin+12:end]
    
 def GetCity(nprovince):
    
     data =[]
    
     Crlf = '&'
    
     data.append('method=getCity2')
    
     data.append('province='+nprovince)
    
     senddata = Crlf.join(data)
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/TrainQuery/autocomplete.do")
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write)
    
     curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
     curl.setopt(pycurl.HEADERFUNCTION, gethead)
    
     curl.setopt(pycurl.HTTPHEADER,["x-requested-with:XMLHttpRequest",
    
                                    "Referer:http://dynamic.12306.cn/TrainQuery/sellTicketStation.jsp"])
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.POSTFIELDS,str(senddata))
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
     curl.close()
    
     return backinfo
    
 def changeGetCity(ninfo):
    
     com = r'''<option.*?value='(.*?)'>.*?</option>'''#
    
     backinfo = []
    
     p = re.compile(com,re.DOTALL)
    
     for m in p.finditer(ninfo):
    
         listinfo = m.group(1)
    
         backinfo.append(listinfo)
    
     return backinfo
    
 def GetCounty(nprovince,ncity):
    
     data =[]
    
     Crlf = '&'
    
     data.append('method=getCountry2')
    
     data.append('city='+ncity)
    
     data.append('province='+nprovince)
    
     senddata = Crlf.join(data)
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/TrainQuery/autocomplete.do")
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write)
    
     curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
     curl.setopt(pycurl.HEADERFUNCTION, gethead)
    
     curl.setopt(pycurl.HTTPHEADER,["x-requested-with:XMLHttpRequest",
    
                                    "Referer:http://dynamic.12306.cn/TrainQuery/sellTicketStation.jsp"])
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.POSTFIELDS,str(senddata))
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
     curl.close()
    
     return backinfo
    
 def GetSellPlaceDetal(nprovince,ncity,ncountry):
    
     data =[]
    
     Crlf = '&'
    
     data.append('province='+nprovince)
    
     data.append('province_new_value=false')
    
     data.append('city='+ncity)
    
     data.append('province_new_value=false')
    
     data.append('country='+ncountry)
    
     data.append('province_new_value=false')
    
     senddata = Crlf.join(data)
    
     curl = pycurl.Curl()
    
     b = StringIO.StringIO()
    
     curl.setopt(pycurl.URL, "https://dynamic.12306.cn/TrainQuery/iframeSellTicketStation.jsp")
    
     curl.setopt(pycurl.WRITEFUNCTION, b.write)
    
     curl.setopt(pycurl.SSL_VERIFYPEER, False)
    
     curl.setopt(pycurl.SSL_VERIFYHOST, False)
    
     curl.setopt(pycurl.HEADERFUNCTION, gethead)
    
     curl.setopt(pycurl.HTTPHEADER,["Referer:http://dynamic.12306.cn/TrainQuery/sellTicketStation.jsp"])
    
     curl.setopt(pycurl.COOKIE,Cookie)
    
     curl.setopt(pycurl.POSTFIELDS,str(senddata))
    
     curl.perform()
    
     backinfo = None
    
     if curl.getinfo(pycurl.RESPONSE_CODE) == 200:
    
         backinfo = b.getvalue()
    
     curl.close()
    
     return backinfo
    
 def changeSellDetal(ninfo):
    
     com = r'''<row id ='\d+'>.*?<cell>(.*?)</cell>.*?<cell>(.*?)</cell>.*?<cell><!\[CDATA\[ (.*?)http.*?</cell>.*?<cell>(.*?)</cell>.*?<cell>(.*?)</cell>.*?</row>'''#
    
     backinfo = []
    
     p = re.compile(com,re.DOTALL)
    
     for m in p.finditer(ninfo):
    
         listinfo = [m.group(1),m.group(2),m.group(3)[:len(m.group(3))-1],m.group(4),m.group(5)]
    
         backinfo.append(listinfo)
    
     return backinfo
    
 def GetSellPlace_ALL():
    
     
    
     print "begin"
    
     getRandAndCookie()
    
     GetAllTrainListCode()
    
     tProvinceString = GetProvince()
    
     if tProvinceString == None:
    
         print ' error'
    
     tProvince = eval(tProvinceString)
    
     f = open('sellinfo.txt','w')
    
     for  i in tProvince:
    
         citystr = GetCity(i[0])
    
         if citystr != None:
    
             city = changeGetCity(citystr)
    
             for j in city:
    
                 countrystr = GetCounty(i[0],j)
    
                 if countrystr != None:
    
                     country = changeGetCity(countrystr)
    
                     for k in country:
    
                         info = GetSellPlaceDetal(i[0],j,k)
    
                         if info != None:
    
                             tinfo =  changeSellDetal(info)
    
                             if tinfo != None:
    
                                 print i[0].decode('UTF-8'),j.decode('UTF-8'),k.decode('UTF-8')
    
                                 for ttinfo in tinfo:
    
                                     f.write(i[0])
    
                                     f.write(';')
    
                                     f.write(j)
    
                                     f.write(';')
    
                                     f.write(k)
    
                                     f.write(';')#str.encode("UTF-8")
    
                                     jsoninfo =  json.dumps(ttinfo, encoding="UTF-8", ensure_ascii=False)
    
                                     f.write(jsoninfo.encode('UTF-8'))
    
                                     f.write('\n')
    
     f.close()
    
     print "ok"
    
 def GetTicketInit():
    
     fromcity= '南昌'#必须使用UTF8
    
     tocity= '北京西'
    
     date = '2013-10-22'
    
     stationName = 'K106'
    
     usename = 'system_12306_cn'#写自己的用户名
    
     password = 'system_12306'#自己的密码
    
     peoples = {}
    
     people1 = {'name':'郝某',#姓名
    
                'idcard':'141124198401284046',#身份号
    
                'cardtype':'1',#身份类型 1 二代身份证 2 一代身份证  c 港澳通行证 G 台湾通行证 B 护照
    
                'seat':'1',#1 硬座 2 软座 3 硬卧 4 软卧 5 高级软卧 O 二等座 M 一等座 P 特等座 9 商务座
    
                'ticket':'1',#1成人票,2 儿童票 3 学生票 4 残军票
    
                'mobileno':'13800138000'}#手机号,可有可无
    
     peoples['people1'] = people1
    
     print GetTicket(usename,password,fromcity,tocity,date,stationName,peoples)
    
 def GetSellPrice():
    
     pass
    
     #print allinfo
    
 def main():
    
     if len(sys.argv) < 2:
    
         print 'mainpython.py [-T / -S /-Q /-G]'
    
         return 
    
     if sys.argv[1] == "-T":
    
         RistTrain()
    
     elif sys.argv[1] == "-S":
    
         GetSellPlace_ALL()
    
     elif sys.argv[1] == "-Q":
    
         GetQuery(GetAllTrainNameList())
    
     elif sys.argv[1] == "-G":
    
         GetTicketInit()
    
 Cookie=""#连接相关
    
 loginRand = ""#一个简单的随机难证
    
 train = ""#所有列转站台ID列表
    
 TrainNumList =""#车次的ID列
    
  
    
  
    
  
    
  
    
 if __name__ == '__main__':
    
     main()

下载: <>

全部评论 (0)

还没有任何评论哟~