图片网址不会返回图片.使用Python请求

use*_*003 0 python image python-requests

我使用Python请求来获取图像,但在某些情况下,sit不起作用.它似乎经常发生.一个例子是

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

它在我的浏览器中正常加载,但是使用请求时,它会返回显示"403 forbidden"和"nginx/1.7.11"的html

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
Run Code Online (Sandbox Code Playgroud)

我也试过这个标题,在某些情况下这是必要的.结果相同.

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'}
Run Code Online (Sandbox Code Playgroud)

(几周前我有一个类似的问题,但PIL不支持特定的图像文件类型.这是不同的.)

编辑:基于评论:

看来该链接仅在您访问过原始网站http://aussietaste.recipes/vegetables/leek-vegetables/leek-and-sweet-potato-gratin/时才有效.我想浏览器然后使用缓存版本.任何解决方法?

小智 5

该网站正在验证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
Run Code Online (Sandbox Code Playgroud)

对我来说,这打印

<Response [200]>
Run Code Online (Sandbox Code Playgroud)