Home Backend Development Python Tutorial Python implements 12306 train ticket query system

Python implements 12306 train ticket query system

Feb 24, 2017 pm 03:12 PM

Recently, I saw that python was used to implement train ticket query. I also implemented it myself. I felt that I gained a lot. I will share each step in detail below. (Note that python3 is used)

First I will show the final result:

Execute on the cmd command line: python tickets.py -dk shanghai chengdu 20161007 > result. txt

Python implements 12306 train ticket query system

means: Query the train information starting with D and K from Shanghai to Chengdu on October 7, 2016, and save it to the result.txt file; the following is result.txt The results in the file:

Python implements 12306 train ticket query system

The following will be the implementation steps:

1, Install third-party libraries pip install Installation: requests, docopt, prettytable

2. docopt can be used to parse parameters entered from the command line:

"""
Usage:
test [-gdtkz] <from> <to> <date>
Options:
-h,--help 显示帮助菜单
-g 高铁
-d 动车
-t 特快
-k 快速
-z 直达
Example:
tickets -gdt beijing shanghai 2016-08-25
"""
import docopt
args = docopt.docopt(__doc__)
print(args)
# 上面 """ """ 包含中的:
#Usage:
# test [-gdtkz] <from> <to> <date>
#是必须要的 test 是可以随便写的,不影响解析
Copy after login

The final printed result is a dictionary for later use:

Python implements 12306 train ticket query system

3. Obtain train information

Our interface for querying remaining votes in 12306:

url: 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version= 1.8968'

The method is: get

Transmitted parameters: queryDate:2016-10-05, from_station:CDW, to_station:SHH

The corresponding abbreviation of the city needs to be additional The interface query results in

3.1 Query the corresponding abbreviation of the city:

The url of this interface = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name. js?station_version=1.8968'

The method is get, use regular expressions on the returned results, and extract the values ​​of the city name and abbreviation (the returned values ​​are similar: 7@cqn|Chongqing South|CRW|chongqingnan|cqn|, What we need is: CRW, chongqingnan), the code is as follows

parse_stations.py:

#coding=utf-8
from prettytable import PrettyTable
class TrainCollection(object):
"""
解析列车信息
"""
# 显示车次、出发/到达站、 出发/到达时间、历时、一等坐、二等坐、软卧、硬卧、硬座
header = &#39;序号 车次 出发站/到达站 出发时间/到达时间 历时 商务座 一等座 二等座 软卧 硬卧 硬座 无座&#39;.split()
def __init__(self,rows,traintypes):
self.rows = rows
self.traintypes = traintypes
def _get_duration(self,row):
"""
获取车次运行的时间
"""
duration = row.get(&#39;lishi&#39;).replace(&#39;:&#39;,&#39;小时&#39;) + &#39;分&#39;
if duration.startswith(&#39;00&#39;):
return duration[4:]
elif duration.startswith(&#39;0&#39;):
return duration[1:]
return duration
@property
def trains(self):
result = []
flag = 0
for row in self.rows:
if row[&#39;station_train_code&#39;][0] in self.traintypes:
flag += 1
train = [
# 序号
flag,
# 车次
row[&#39;station_train_code&#39;],
# 出发、到达站点
&#39;/&#39;.join([row[&#39;from_station_name&#39;],row[&#39;to_station_name&#39;]]),
# 成功、到达时间
&#39;/&#39;.join([row[&#39;start_time&#39;],row[&#39;arrive_time&#39;]]),
# duration 时间
self._get_duration(row),
# 商务座
row[&#39;swz_num&#39;],
# 一等座
row[&#39;zy_num&#39;],
# 二等座
row[&#39;ze_num&#39;],
# 软卧
row[&#39;rw_num&#39;],
# 硬卧
row[&#39;yw_num&#39;],
# 硬座
row[&#39;yz_num&#39;],
# 无座
row[&#39;wz_num&#39;]
]
result.append(train)
return result
def print_pretty(self):
"""打印列车信息"""
pt = PrettyTable()
pt._set_field_names(self.header)
for train in self.trains:
pt.add_row(train)
print(pt)
if __name__ == &#39;__main__&#39;:
t = TrainCollection()
Copy after login
Copy after login

The pprint module can be printed Information, easier to read:

Run in cmd: python parse_stations.py > stations.py

will get the stations.py file in the current directory. The file contains the site name and For short, add "stations = " to the stations.py file to create a dictionary to facilitate later values. Here is the content of the stations.py file:

Python implements 12306 train ticket query system

3.2 Now The parameters for obtaining train information have been prepared. The next step is to get the return value of the train and parse out the information you need, such as train number, first-class ticket number, etc. . , myprettytable.py

#coding=utf-8
from prettytable import PrettyTable
class TrainCollection(object):
"""
解析列车信息
"""
# 显示车次、出发/到达站、 出发/到达时间、历时、一等坐、二等坐、软卧、硬卧、硬座
header = &#39;序号 车次 出发站/到达站 出发时间/到达时间 历时 商务座 一等座 二等座 软卧 硬卧 硬座 无座&#39;.split()
def __init__(self,rows,traintypes):
self.rows = rows
self.traintypes = traintypes
def _get_duration(self,row):
"""
获取车次运行的时间
"""
duration = row.get(&#39;lishi&#39;).replace(&#39;:&#39;,&#39;小时&#39;) + &#39;分&#39;
if duration.startswith(&#39;00&#39;):
return duration[4:]
elif duration.startswith(&#39;0&#39;):
return duration[1:]
return duration
@property
def trains(self):
result = []
flag = 0
for row in self.rows:
if row[&#39;station_train_code&#39;][0] in self.traintypes:
flag += 1
train = [
# 序号
flag,
# 车次
row[&#39;station_train_code&#39;],
# 出发、到达站点
&#39;/&#39;.join([row[&#39;from_station_name&#39;],row[&#39;to_station_name&#39;]]),
# 成功、到达时间
&#39;/&#39;.join([row[&#39;start_time&#39;],row[&#39;arrive_time&#39;]]),
# duration 时间
self._get_duration(row),
# 商务座
row[&#39;swz_num&#39;],
# 一等座
row[&#39;zy_num&#39;],
# 二等座
row[&#39;ze_num&#39;],
# 软卧
row[&#39;rw_num&#39;],
# 硬卧
row[&#39;yw_num&#39;],
# 硬座
row[&#39;yz_num&#39;],
# 无座
row[&#39;wz_num&#39;]
]
result.append(train)
return result
def print_pretty(self):
"""打印列车信息"""
pt = PrettyTable()
pt._set_field_names(self.header)
for train in self.trains:
pt.add_row(train)
print(pt)
if __name__ == &#39;__main__&#39;:
t = TrainCollection()
Copy after login
Copy after login

prettytable This library can print out a format similar to that displayed by mysql query data,

4. The next step is to integrate the various modules: tickets.py

"""Train tickets query via command-line.
Usage:
tickets [-gdtkz] <from> <to> <date>
Options:
-h,--help 显示帮助菜单
-g 高铁
-d 动车
-t 特快
-k 快速
-z 直达
Example:
tickets -gdt beijing shanghai 2016-08-25
"""
import requests
from docopt import docopt
from stations import stations
# from pprint import pprint
from myprettytable import TrainCollection
class SelectTrain(object):
def __init__(self):
"""
获取命令行输入的参数
"""
self.args = docopt(__doc__)#这个是获取命令行的所有参数,返回的是一个字典
def cli(self):
"""command-line interface"""
# 获取 出发站点和目标站点
from_station = stations.get(self.args[&#39;<from>&#39;]) #出发站点
to_station = stations.get(self.args[&#39;<to>&#39;]) # 目的站点
leave_time = self._get_leave_time()# 出发时间
url = &#39;https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={0}&from_station={1}&to_station={2}&#39;.format(
leave_time,from_station,to_station)# 拼接请求列车信息的Url
# 获取列车查询结果
r = requests.get(url,verify=False)
traindatas = r.json()[&#39;data&#39;][&#39;datas&#39;] # 返回的结果,转化成json格式,取出datas,方便后面解析列车信息用
# 解析列车信息
traintypes = self._get_traintype()
views = TrainCollection(traindatas,traintypes)
views.print_pretty()
def _get_traintype(self):
"""
获取列车型号,这个函数的作用是的目的是:当你输入 -g 是只是返回 高铁,输入 -gd 返回动车和高铁,当不输参数时,返回所有的列车信息
""" 
traintypes = [&#39;-g&#39;,&#39;-d&#39;,&#39;-t&#39;,&#39;-k&#39;,&#39;-z&#39;]
# result = []
# for traintype in traintypes:
# if self.args[traintype]:
# result.append(traintype[-1].upper())
trains = [traintype[-1].upper() for traintype in traintypes if self.args[traintype]]
if trains:
return trains
else:
return [&#39;G&#39;,&#39;D&#39;,&#39;T&#39;,&#39;K&#39;,&#39;Z&#39;]
def _get_leave_time(self):
"""
获取出发时间,这个函数的作用是为了:时间可以输入两种格式:2016-10-05、20161005
"""
leave_time = self.args[&#39;<date>&#39;]
if len(leave_time) == 8:
return &#39;{0}-{1}-{2}&#39;.format(leave_time[:4],leave_time[4:6],leave_time[6:])
if &#39;-&#39; in leave_time:
return leave_time
if __name__ == &#39;__main__&#39;:
cli = SelectTrain()
cli.cli()
Copy after login

Okay, it’s basically over. According to the beginning, you can query I want the train information

The above is the Python script introduced by the editor to implement the 12306 train ticket query system. I hope it will be helpful to everyone. If you have any questions, please leave me a message. Editor Will reply to everyone promptly. I would also like to thank you all for your support of the PHP Chinese website!

For more articles related to the implementation of 12306 train ticket query system in Python, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Learning Python: Is 2 Hours of Daily Study Sufficient? Learning Python: Is 2 Hours of Daily Study Sufficient? Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Which is part of the Python standard library: lists or arrays? Which is part of the Python standard library: lists or arrays? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python for Web Development: Key Applications Python for Web Development: Key Applications Apr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

See all articles