12306自动抢票实现(一)

途中创建一个sl.py文件

# -*- coding: utf-8 -*-

cons = '@bji|北京|BJP|0@sha|上海|SHH|1@tji|天津|TJP|2@cqi|重庆|CQW|3@csh|长沙|CSQ|4@cch|长春|CCT|5@cdu|成都|CDW|6@fzh|福州|FZS|7@gzh|广州|GZQ|8@gya|贵阳|GIW|9@hht|呼和浩特|HHC|10@heb|哈尔滨|HBB|11@hfe|合肥|HFH|12@hzh|杭州|HZH|13@hko|海口|VUQ|14@jna|济南|JNK|15@kmi|昆明|KMM|16@lsa|拉萨|LSO|17@lzh|兰州|LZJ|18@nni|南宁|NNZ|19@nji|南京|NJH|20@nch|南昌|NCG|21@sya|沈阳|SYT|22@sjz|石家庄|SJP|23@tyu|太原|TYV|24@wlq|乌鲁木齐南|WMR|25@wha|武汉|WHN|26@xni|西宁|XNO|27@xan|西安|XAY|28@ych|银川|YIJ|29@zzh|郑州|ZZF|30@szh|深圳|SZQ|shenzhen|sz|31@xme|厦门|XMS|xiamen|xm|32'

创建第一个12306.py文件

# -*- coding: utf-8 -*-

import urllib2
import ssl
import json
from sl import cons

ssl._create_default_https_context = ssl._create_unverified_context #跳过证书验证

station_dict = {}

for i in cons.split('@'):
    if i:
        tmp_list = i.split('|')
        station_dict[tmp_list[1]] = tmp_list[2]
#print station_dict['成都']

train_date = '2017-07-31'
from_station = station_dict['北京']
to_station = station_dict['石家庄']

def getList():
    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))
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36')
    html = urllib2.urlopen(req).read()
    #print html
    dict = json.loads(html)
    #print dict
    return dict['data']['result']

cs = 0
#车次  =  3
#出发时间 = 8
#到达时间 = 9
#历时 = 10
#软卧 = 23
#硬卧 = 28
#硬座 无座 26 29


for i in getList():
    #for n in i.split('|'):
     #   print '[%s]' %cs,n
      #  cs += 1
    if tmp_list == u'无' or tmp_list == '--':
        continue
    tmp_list = i.split('|')
    if int(tmp_list[23]) > 0:
        print '有票' #买票
    break



你可能感兴趣的:(12306自动抢票实现(一))