擅长:python、mysql、java
<p>如果尚未安装,<a href="http://docs.python-requests.org/en/latest/user/install/" rel="nofollow">^{<cd1>}</a>,可以使用<a href="http://docs.python-requests.org/en/latest/" rel="nofollow">Requests</a></p>
<p>因为这个<code>img_url</code>被服务器重定向到另一个html页面(即您刚刚下载的html页面),如果您没有提供<code>referer</code>头。在</p>
<p>所以下面的代码首先找到重定向url,并将其添加到httpreferer头中。在</p>
<pre><code>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)
</code></pre>