2016-08-01 6 views
-1

私はpythonでrequestパッケージを使用してulrsを要求しています(例:file = requests.get(url))。 URLには拡張子が指定されておらず、場合によってはHTMLファイルが返され、時にはpdfが返されることがあります。urlがpdfかhtmlファイルかどうかを確認する

返されるファイルがpdfかhtmlかどうかを判断する方法はありますか? (またはより一般的には、ファイル形式は何ですか)。ブラウザが決定できるので、私は応答で指示しなければならないと仮定します。

答えて

3

これはtext/html又はapplication/pdf

import requests 

r = requests.get('http://example.com/file') 
content_type = r.headers.get('content-type') 

if 'application/pdf' in content_type: 
    ext = '.pdf' 
elif 'text/html' in content_type: 
    ext = '.html' 
else: 
    ext = '' 
    print('Unknown type: {}'.format(content_type)) 

with open('myfile'+ext, 'wb') as f: 
    f.write(r.raw.read()) 
いずれか、 Content-Typeヘッダに見出されます
関連する問題