下载反盗链图片时,Headers除了必备的User-Agent字段之外,还需添加Referer字段,该字段为当前图片所在的页面链接。
运行以下代码:
import requests
# 图片地址
url = 'https://stubbornhuangcomwordpressmedialibrary.oss-cn-shenzhen.aliyuncs.com/WordpressMediaLibrary/2019/12/201912260937073.png'
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
reponse = requests.get(url,headers=headers)
print(reponse.status_code)
with open("1.jpg","wb")as f:
f.write(reponse.content)
reponse.close()
这是下载我个人站的图片,但是我在阿里OSS中配置了图片反盗链,所以如果我们以这种形式去下载图片,最后的响应代码一般都是403,这就是因为该资源进行了反盗链,那么自然图片也是无法下载成功的。
运行以下代码:
import requests
# 图片地址
url = 'https://stubbornhuangcomwordpressmedialibrary.oss-cn-shenzhen.aliyuncs.com/WordpressMediaLibrary/2019/12/201912260937073.png'
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0',
'Referer':'https://www.stubbornhuang.com/532/'
}
reponse = requests.get(url,headers=headers)
print(reponse.status_code)
with open("1.jpg","wb")as f:
f.write(reponse.content)
reponse.close()
结果发现,请求响应代码为200,说明我们请求成功,成功下载到了资源。
更多干货内容请访问:www.stubbornhuang.com