|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import requests
import json
class TrainService(object):
def __init__(self):
with open('code.json','r') as file:
code=eval(file.read())
self.code=code
self.code_url="https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9002"
self.headers={'User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.7 Safari/537.36'}
def crawlTrainMess(self,from_station,to_station,train_date):
self.url="https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT".format(train_date,self.code[from_station],self.code[to_station])
response=requests.get(self.url,headers=self.headers)
train_json=json.load(response.text)
results=train_json['data']['result']
train_list=[]
for i in results:
temp=i.split('|')
train_list.append([temp[3], temp[8], temp[9], temp[25], temp[26]])
#print(train_list)
return train_list
def crawlCodeMess(self):
response=requests.get(self.code_url,headers=self.headers)
station_list=response.text.split('@')[1:]
code={}
for i in station_list:
temp=i.split('|')
code[temp[1]]=temp[2]
#print(code)
with open('code.json','w') as file:
file.write(str(code))
if __name__=='__main__':
ts=TrainService()
ts.crawlCodeMess()
你的城市数据都没有下载下来,你怎么去读它,没有文件,肯定会报错。不应该放在实例化里面,至少得先请求在本地才可以
其次如果你是读出来用的话可以使用这样的格式:
- with open(path,"r",encoding="UTF-8") as f:
- result = json.loads(f.read(),encoding="UTF-8")
复制代码
如果你是写入用的话可以使用这样的格式:
- with open(path,"w",encoding="UTF-8") as f:
- json.dump(city_dict,f)
复制代码
|
|