Python 代码优化:一次输入获取起点和终点机场代码
这是一个使用 Python 语言获取起点和终点城市名称以及对应的机场代码的代码示例。最初的代码需要用户输入两次才能获取所有信息,这会让用户体验不佳。
以下代码优化了这个过程,只需输入一次即可获取所有信息:
import requests
def get_city_code(city):
url = f'https://www.westair.cn/air/api/v0/LocationAPI/locations?locationType=AIRPORT&searchableOnly=true&city={city}'
payload={}
headers = {
'Accept-Language': 'zh-CN',
'Referer': 'https://www.westair.cn/flights/results/CKG-CAN-230404-100-0',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
}
response = requests.request('GET', url, headers=headers, data=payload)
city_code = response.json()['locations'][0]['iataCode']
return city_code
if __name__ == '__main__':
start_city = input('请输入起点城市名称:')
end_city = input('请输入终点城市名称:')
start_code = get_city_code(start_city)
end_code = get_city_code(end_city)
print(f'起点城市名称:{start_city},机场代码:{start_code}')
print(f'终点城市名称:{end_city},机场代码:{end_code}')
代码优化后的关键在于:
- 将获取机场代码的逻辑封装到
get_city_code()函数中,该函数接收城市名称作为参数,并返回对应的机场代码。 - 在
if __name__ == '__main__':代码块中,用户只需要输入一次起点和终点城市名称,程序会分别调用get_city_code()函数获取对应的机场代码,并输出结果。
这样,用户体验就得到了改善,只需要输入一次即可完成所有操作。
原文地址: https://www.cveoy.top/t/topic/mvrM 著作权归作者所有。请勿转载和采集!