[問題] requests 和非法的 headers

看板Python作者 (人類)時間8年前 (2017/04/17 22:17), 編輯推噓1(108)
留言9則, 4人參與, 最新討論串1/1
雖然標題寫 requests,不過 python 3.6 的 urllib 也有這現象。 問題出自於 server 回傳的 header 不太正常。這是 curl -D 拿到的︰ HTTP/1.1 302 Moved Temporarily Server: nginx/1.8.0 Date: Mon, 17 Apr 2017 11:18:21 GMT Content-Type: text/html Connection: keep-alive Status 302: Location: ... 而用 requests 拿到的 response.headers,缺少 "Location" 這個 key,無法處理轉址。 如果用 urllib,拿到的 response.info() 也是缺少 Location,且 as_string() 長這樣︰ Server: nginx/1.8.0 Date: Mon, 17 Apr 2017 12:24:27 GMT Content-Type: text/html Transfer-Encoding: chunked Connection: close Status 302: Location: ... Firefox 則是可以正常辨認 Location,Node.js 也是︰ { server: 'nginx/1.8.0', date: 'Mon, 17 Apr 2017 13:59:56 GMT', 'content-type': 'text/html', 'transfer-encoding': 'chunked', connection: 'keep-alive', 'status 302': '', location: '...' } 感覺是 parser 的問題。不知道這種情況怎麼處理?或是有任何辦法在 requests 中存取 raw data 找出 Location? 最後附上網址,是個漫畫網站,內可能含有較清涼圖片︰ ht tp://smp.yoedge.com/smp-app/1017018/shinmangaplayer/index.html -- (* ̄▽ ̄)/‧★*"`'*-.,_,.-*'`"*-.,_☆,.-*` http://i.imgur.com/oAd97.png
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.160.246.132 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1492438624.A.BBC.html

04/18 00:03, , 1F
r.raw._original_response.msg.to_string()
04/18 00:03, 1F

04/18 00:10, , 2F
py2 沒這問題, 應該是 py3 urllib parser 的 bug
04/18 00:10, 2F

04/18 00:11, , 3F
可以 report 回 bug.python
04/18 00:11, 3F

04/18 01:00, , 4F
其實也不能說是 bug, 這個 header 本身就 malformed 了
04/18 01:00, 4F

04/18 01:00, , 5F
HTTP header key 不應該包含空白, 讀到 status 302 那行
04/18 01:00, 5F

04/18 01:01, , 6F
會爆掉也是合情合理的事情...
04/18 01:01, 6F

04/18 01:08, , 7F
看到上面我才驚覺,原來 status 那行算在 heaser 裡面?
04/18 01:08, 7F

04/18 15:41, , 8F
HTTP status 不是那樣寫的啊, 根本不知道為什麼有那行
04/18 15:41, 8F

04/18 19:27, , 9F
感謝一樓
04/18 19:27, 9F
文章代碼(AID): #1OzCvWky (Python)
文章代碼(AID): #1OzCvWky (Python)