2016-08-01 108 views
-1

我使用python中的請求包(例如file = requests.get(url))請求ulrs。網址沒有在其中指定擴展名,有時會返回一個html文件,有時會返回pdf。確定url是pdf還是html文件

有沒有確定返回的文件是pdf還是html的方法? (或者更一般地說,文件格式是什麼)。瀏覽器能夠確定,所以我認爲必須在響應中指明。

回答

3

這將在Content-Type報頭中找到,無論是text/htmlapplication/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()) 
相關問題