贊助廠商

娛樂城推薦

首頁

電腦與網際網路/其他:電腦列表

Python- 高鐵網站回應出現405錯誤訊息

[已解決,附上正確程式碼。][目前高鐵仍沒有擋 "未經過偽裝的" headers, 但是底下為了完整性仍附上 headers]我根據 https://github.com/jwlin/py-scraping-analysis-book/blob/master/ch7/thrsc.py的範例程式碼,以高鐵網站測試 requests post 方法,由於網站改版,因此修改程式碼如下:import requestsfrom bs4 import BeautifulSoupheaders ={ 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36' }def get_station_id(headers=headers): URL = 'https://www.thsrc.com.tw/tw/TimeTable/SearchResult' station_to_id = {} resp = requests.get(URL, headers=headers) soup = BeautifulSoup(resp.text, 'html5lib') for opt in soup.find('select', id='select_location01').find_all('option'): station_to_id[opt.text.strip()] = opt['value'] return station_to_iddef get_times(start_station, end_station, search_date, search_time, headers=headers): URL = 'https://www.thsrc.com.tw/TimeTable/Search' form_data = { 'SearchType': 'S', 'Lang': 'TW', 'StartStation': station_to_id[start_station], 'EndStation': station_to_id[end_station], 'OutWardSearchDate': search_date, 'OutWardSearchTime': search_time, 'ReturnSearchDate': search_date, 'ReturnSearchTime': search_time, 'DiscountType': '' } resp = requests.post(URL, data=form_data, headers=headers) print(resp) data = resp.json() # import json # with open('test' + '.json', 'w', encoding='utf-8') as f: # json.dump(data, f, indent=2, sort_keys=True, ensure_ascii=False) columns = ['TrainNumber', 'DepartureTime', 'DestinationTime', 'Duration'] times = [] for d in data['data']['DepartureTable']['TrainItem']: times.append([d[c] for c in columns]) return timesif __name__ == '__main__': station_to_id = get_station_id() times = get_times('台北', '左營', '2021/05/10', '10:30') print('車次, 出發時間, 抵達時間, 行車時間') for t in times: print(t)使用這個程式碼可以用 get 方法獲取完整的 station_to_id,但是 resp 會出現 <Response [405]>, 因此 post 方法收不到任何東西。請問:以這個例子而言,405錯誤訊息的解法為何?--
  • 發問日期:2021-06-03 17:10:06

友站連結