-
Notifications
You must be signed in to change notification settings - Fork 22
/
bus.py
205 lines (160 loc) · 6.47 KB
/
bus.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import requests
import pickle
import os
import time
from bs4 import BeautifulSoup
from bus_routers import Routers
from InvalidParameterException import InvalidParameterException
class Bus:
def __init__(self):
self.headers = {
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 '
'(KHTML, like Gecko) Mobile/14F89 MicroMessenger/6.5.10 NetType/WIFI Language/zh_CN'
}
self.homepage_url = 'https://shanghaicity.openservice.kankanews.com/'
self.query_router_url = 'https://shanghaicity.openservice.kankanews.com/public/bus'
self.query_sid_url = 'https://shanghaicity.openservice.kankanews.com/public/bus/get'
self.query_router_details_url = 'https://shanghaicity.openservice.kankanews.com/public/bus/mes/sid/'
self.query_stop_url = 'https://shanghaicity.openservice.kankanews.com/public/bus/Getstop'
def _homepage(self):
r = self.s.get(self.homepage_url, headers=self.headers)
return r
def _query_router_page(self):
self.headers['Referer'] = self.homepage_url
r = self.s.get(self.query_router_url, headers=self.headers)
return r
def _query_sid(self, router_name):
data = {'idnum': router_name}
r = self.s.post(self.query_sid_url, data=data, headers=self.headers)
sid = r.json()['sid']
return sid
def _query_router_details_page(self, sid, direction='0'):
self.headers['Referer'] = self.query_router_url
url = self.query_router_details_url + sid + '?stoptype=' + direction
r = self.s.get(url, headers=self.headers)
return r
def _query_stop(self, sid, direction, stop_id):
data = {'stoptype': direction, 'stopid': stop_id, 'sid': sid}
self.headers['Content-Type'] = 'application/x-www-form-urlencoded'
self.headers['Referer'] = self.query_router_details_url
r = self.s.post(self.query_stop_url, data=data, headers=self.headers)
return r
def _init_request(self, router_name):
self._check_routers(router_name)
if os.path.exists('session.log'):
with open('session.log', 'rb') as f:
session = pickle.load(f)
if session['expired_at']+1800 < time.time():
# session expired
self._make_session()
else:
# read session from cache
self.s = session['session']
else:
# session not exists
self._make_session()
# 第三步:查询公交路线对应的sid
sid = self._query_sid(router_name)
return sid
def _make_session(self):
self.s = requests.Session()
# 第一步:加载首页
self._homepage()
# 第二部:加载查询页面
self._query_router_page()
with open('session.log', 'wb') as f:
session = {
'session': self.s,
'expired_at': time.time()
}
pickle.dump(session, f)
def _check_routers(self, router_name):
if router_name not in Routers:
raise InvalidParameterException('router_not_exists', '不存在该公交线路', 400)
def query_stop(self, router_name, direction, stop_id):
sid = self._init_request(router_name)
# 查询公交到站信息
r = self._query_stop(sid, direction, stop_id)
res = r.json()
if type(res) is list:
res = res[0]
return {
'router_name': res['@attributes']['cod'],
'direction': direction,
'plate_number': res['terminal'],
'stop_interval': res['stopdis'],
'distance': res['distance'],
'time': res['time'],
'status': 'running'
}
else:
return {
'router_name': router_name,
'direction': direction,
'plate_number': '',
'stop_interval': '',
'distance': '',
'time': '',
'status': 'waiting'
}
def query_router(self, router_name, direction='0'):
self.sid = self._init_request(router_name)
# 进入公交线路明细页面
r = self._query_router_details_page(self.sid, direction)
soup = BeautifulSoup(r.text.encode(r.encoding), 'lxml')
stations = soup.select('div.upgoing.cur span')
from_station = stations[0].string
to_station = stations[1].string
strat_at = soup.select('div.upgoing.cur em.s')[0].string
end_at = soup.select('div.upgoing.cur em.m')[0].string
stations = soup.select('div.station')
stops = []
for station in stations:
router = {}
for c in station.children:
if c.name == 'span':
if c.attrs['class'][0] == 'num':
router['stop_id'] = c.string
elif c.attrs['class'][0] == 'name':
router['stop_name'] = c.string
stops.append(router)
return {
'from': from_station,
'to': to_station,
'start_at': strat_at,
'end_at': end_at,
'direction': direction,
'stops': stops
}
def query_router_details(self, router_name, direction='0'):
router = self.query_router(router_name, direction)
stops = router['stops']
for stop in stops:
# 查询公交到站信息
r = self._query_stop(self.sid, direction, stop['stop_id'])
res = r.json()
if type(res) is list:
res = res[0]
stop['plate_number'] = res['terminal']
stop['stop_interval'] = res['stopdis']
stop['distance'] = res['distance']
stop['time'] = res['time']
stop['status'] = 'running'
else:
stop['plate_number'] = ''
stop['stop_interval'] = ''
stop['distance'] = ''
stop['time'] = ''
stop['status'] = 'waiting'
return router
if __name__ == '__main__':
router_name = '406路'
direction = '0'
stop_id = '4'
bus = Bus()
stops = bus.query_router(router_name)
print(stops)
r = bus.query_stop(router_name, direction, stop_id)
print(r)
r = bus.query_router_details(router_name, direction)
print(r)