簡體   English   中英

圖片網址不返回圖片。 使用Python請求

[英]Image url does not return an image. Using Python requests

我使用Python請求獲取圖像,但在某些情況下,sit無法正常工作。 它似乎更經常發生。 一個例子是

http://recipes.thetasteofaussie.netdna-cdn.com/wp-content/uploads/2015/07/Leek-and-Sweet-Potato-Gratin.jpg

它在我的瀏覽器中可以正常加載,但是使用請求時,它返回的HTML內容為“ 403 forbidden”和“ nginx / 1.7.11”

import requests
image_url = "<the_url>"
headers = {'User-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36', 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','Accept-Encoding':'gzip,deflate,sdch'}
r = requests.get(image_url, headers=headers)
# r.content is html '403 forbidden', not an image

我也嘗試過使用此標頭,在某些情況下這是必需的。 結果相同。

headers = {'User-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36', 'Accept':'image/webp,*/*;q=0.8','Accept-Encoding':'gzip,deflate,sdch'}

(幾周前,我也遇到了類似的問題,但這是由PIL不支持的特定圖像文件類型回答的。這是不同的。)

編輯:基於評論:

似乎該鏈接僅在您已訪問原始站點http://aussietaste.recipes/vegetables/leek-vegetables/leek-and-sweet-potato-gratin/的情況下起作用。 我想瀏覽器然后使用緩存的版本。 任何解決方法?

該站點正在驗證Referer標頭。 這樣可以防止其他站點將圖像包括在其網頁中並使用圖像主機的帶寬。 將其設置為您在帖子中提到的網站,它將起作用。

更多信息: https//en.wikipedia.org/wiki/HTTP_referer

import requests
image_url = "http://recipes.thetasteofaussie.netdna-cdn.com/wp-content/uploads/2015/07/Leek-and-Sweet-Potato-Gratin.jpg"
headers = {
    'User-agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36',
    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Encoding' : 'gzip,deflate,sdch',
    'Referer' : 'http://aussietaste.recipes/vegetables/leek-vegetables/leek-and-sweet-potato-gratin/'
}
r = requests.get(image_url, headers=headers)
print r

對我來說,這印

<Response [200]>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM