尝试从图像url(使用pythonurllib)抓取图像,但是得到html

2024-04-29 19:49:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从下面的url获取图像。在

http://upic.me/i/fj/the_wonderful_mist_once_again_01.jpg

我可以右键单击并另存为,但当我尝试使用urlretrieve时

import urllib
img_url = 'http://upic.me/i/fj/the_wonderful_mist_once_again_01.jpg'
urllib.urlretrieve( img_url, 'cover.jpg')

我发现它是html而不是.jpg图像,但我不知道为什么。 你能告诉我为什么我的方法行不通吗?有没有可以模仿右键单击另存为方法的选项?在


Tags: the图像httpurlurllibjpgmeagain
2条回答

试着这样做:

import urllib2

image = urllib2.urlopen('http://upic.me/i/fj/the_wonderful_mist_once_again_01.jpg').read()
f = open('some_name.jpg','w')
f.write(image)
f.close()

如果尚未安装,^{},可以使用Requests

因为这个img_url被服务器重定向到另一个html页面(即您刚刚下载的html页面),如果您没有提供referer头。在

所以下面的代码首先找到重定向url,并将其添加到httpreferer头中。在

import requests
img_url = 'http://upic.me/i/fj/the_wonderful_mist_once_again_01.jpg'

r = requests.get(img_url, allow_redirects=False)   #  stop redirect 302 , capture redirects url

headers = {}
headers['Referer'] = r.headers['location']    # add this url to referer 'http://upic.me/show/55132055'

r = requests.get(img_url, headers=headers)
filename = img_url.split('/')[-1]             # find the file name in `img_url`
with open(filename, 'wb') as fh:             # use 'wb' to write in binary mode
    fh.write(r.content)

相关问题 更多 >