看板 Python 關於我們 聯絡資訊
[已解決,附上正確程式碼。] [目前高鐵仍沒有擋 "未經過偽裝的" headers, 但是底下為了完整性仍附上 headers] 我根據  https://github.com/jwlin/py-scraping-analysis-book/blob/master/ch7/thrsc.py 的範例程式碼,以高鐵網站測試 requests post 方法, 由於網站改版,因此修改程式碼如下: import requests from bs4 import BeautifulSoup headers ={ '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_id def 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 times if __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錯誤訊息的解法為何? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.136.52.207 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1620264381.A.577.html
melancholy07: 我還沒看post的data格式跟內容有沒有問題 05/06 13:56
melancholy07: 但你要不要先帶headers再試試看? 05/06 13:56
有做過這個測試,但是判定原因不在此, 原本因為貼上去會造成排版問題所以沒貼... 剛才又補上一次headers,仍然看到405...現 在補上 headers 的版本。
pinefruit: 你的 SearchType 是不是忘了填值? 05/06 14:58
抱歉,有填,但是貼上來消除多餘註解不小心拿掉,現在已經補上。 ※ 編輯: gg (101.136.169.64 臺灣), 05/06/2021 16:02:20
lycantrope: 確定url沒錯? 05/06 16:02
Bingo! 查閱時間的網址沒變,但是網站幕後運作的網址少了一小截: 我原本貼的是 https://www.thsrc.com.tw/tw/TimeTable/Search 正確應該是 https://www.thsrc.com.tw/TimeTable/Search 只用眼睛掃描果然不對 感謝! ※ 編輯: gg (101.136.169.64 臺灣), 05/06/2021 16:06:27
lycantrope: url好像又好了. 05/06 16:06
※ 編輯: gg (101.136.169.64 臺灣), 05/06/2021 16:15:36