Skip to content

Commit 8b8af6f

Browse files
authored
Merge pull request #4 from darren2023/update_stations
update station to version: 1.9311
2 parents 7b1b227 + 949c7cb commit 8b8af6f

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

x12306/data/stations.txt

+1-1
Large diffs are not rendered by default.

x12306/update_station.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import requests
2+
import re
3+
4+
DEFAULT_BASE_URL = "https://kyfw.12306.cn/otn/leftTicket"
5+
DEFAULT_STATION_URL = "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js"
6+
7+
8+
def update_station(path: str = "./x12306/data/stations.txt") -> None:
9+
# update station information
10+
init_url = DEFAULT_BASE_URL + "/init"
11+
response = requests.get(init_url)
12+
if response.status_code == 200:
13+
pattern = re.compile(r"station_version=([\d\.]+)")
14+
station_version = pattern.search(response.text)
15+
if station_version:
16+
print(f"Station version: {station_version.group(1)}")
17+
station_url = (
18+
DEFAULT_STATION_URL + f"?station_version={station_version.group(1)}"
19+
)
20+
21+
response = requests.get(station_url)
22+
if response.status_code == 200:
23+
pattern = re.compile(r"var station_names ='(.*?)';")
24+
station_names = pattern.search(response.text)
25+
if station_names:
26+
# utf-8 encoding
27+
with open(path, "w", encoding="utf-8") as f:
28+
f.write(station_names.group(1))
29+
print(f"Station information saved to {path}")
30+
else:
31+
print("Failed to retrieve the station information.")
32+
print(response.text)
33+
else:
34+
print(
35+
f"Failed to retrieve the page. Status code: {response.status_code}"
36+
)
37+
else:
38+
print("Station version not found.")
39+
else:
40+
print(f"Failed to retrieve the page. Status code: {response.status_code}")
41+
42+
43+
if __name__ == "__main__":
44+
update_station()

0 commit comments

Comments
 (0)