作者gg (GG)
看板Python
标题[问题] 高铁网站回应出现405错误讯息
时间Thu May 6 09:26:19 2021
[已解决,附上正确程式码。]
[目前高铁仍没有挡 "未经过伪装的" 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://webptt.com/cn.aspx?n=bbs/Python/M.1620264381.A.577.html
1F:推 melancholy07: 我还没看post的data格式跟内容有没有问题 05/06 13:56
2F:→ melancholy07: 但你要不要先带headers再试试看? 05/06 13:56
有做过这个测试,但是判定原因不在此,
原本因为贴上去会造成排版问题所以没贴...
刚才又补上一次headers,仍然看到405...现
在补上 headers 的版本。
3F:推 pinefruit: 你的 SearchType 是不是忘了填值? 05/06 14:58
抱歉,有填,但是贴上来消除多余注解不小心拿掉,现在已经补上。
※ 编辑: gg (101.136.169.64 台湾), 05/06/2021 16:02:20
4F:推 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
5F:推 lycantrope: url好像又好了. 05/06 16:06
※ 编辑: gg (101.136.169.64 台湾), 05/06/2021 16:15:36