到目前為止,我一直在使用 PIL 和 requests 庫下載某些維基百科影像,沒有問題。在某些時候某處發生了變化,現在在嘗試下載和加載以下影像時出現錯誤:
from PIL import Image
import requests
url_1 = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/" \
"Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/2728px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg"
#url_2 = "https://upload.wikimedia.org/wikipedia/commons/9/9d/The_Scream_by_Edvard_Munch,_1893_-_Nasjonalgalleriet.png"
#url_3 = "https://upload.wikimedia.org/wikipedia/en/8/8f/Pablo_Picasso,_1909-10,_Figure_dans_un_Fauteuil_(Seated_Nude%" \
# "2C_Femme_nue_assise),_oil_on_canvas,_92.1_x_73_cm,_Tate_Modern,_London.jpg"
response = requests.get(url_1, stream=True)
img = Image.open(response.raw)
以及由此產生的錯誤訊息:
---------------------------------------------------------------------------
UnidentifiedImageError Traceback (most recent call last)
<ipython-input-2-9f0ecb1762aa> in <module>()
13
14 response = requests.get(url_1, stream=True)
---> 15 img = Image.open(response.raw)
/usr/local/lib/python3.7/dist-packages/PIL/Image.py in open(fp, mode)
2894 warnings.warn(message)
2895 raise UnidentifiedImageError(
-> 2896 "cannot identify image file %r" % (filename if filename else fp)
2897 )
2898
UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f9b71d22bf0>
錯誤本身不是很具有描述性,我一直無法弄清楚如何修復它。任何幫助將不勝感激。URLs 本身導致一個完全正常的影像,并且代碼一直作業到這一點。
uj5u.com熱心網友回復:
您的問題是維基百科希望在您的請求中包含一個用戶代理標頭。如果您在請求中提供了 user-agent 標頭,那么您將按預期回傳影像。
您可以通過查看回應文本來確定這是問題所在。例如,我復制/粘貼了您的請求并查看了回應文本。文本顯示“錯誤:403,禁止。請遵守用戶代理政策”。這就是我知道您缺少的是用戶代理的方式。
對于用戶代理,您可能應該提供比我在示例中使用的占位符更具描述性的內容。也許是你的腳本的名稱,或者只是“腳本”這個詞或類似的東西。
headers = {
'User-Agent': 'My User Agent 1.0'
}
picture_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/2728px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg"
r = requests.get(picture_url, headers=headers, stream=True)
Image.open(r.raw)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/343223.html
下一篇:將json記錄陣列規范化為資料幀
