防盗链

#coding:utf-8
import urllib.request
"""
# 下载普通图片
url = "http://pic22.nipic.com/20120725/9676681_001949824394_2.jpg"
response = urllib.request.urlopen(url)
with open("k.jpg", "wb")as fp:
    fp.write(response.read())
"""
'''
#下载普通图片2
url = "http://pic22.nipic.com/20120725/9676681_001949824394_2.jpg"
urllib.request.urlretrieve(url, "m.jpg")
'''

# 有防盗链机制的图片下载
url = "https://i5.meizitu.net/2019/07/09b01.jpg"

#urllib.request.urlretrieve(url, "mv.jpg")  # urllib.error.HTTPError: HTTP Error 403: Forbidden

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
    'Referer': 'https://www.mzitu.com/'

}
request = urllib.request.Request(url=url, headers=headers)
response = urllib.request.urlopen(request)
with open("mv.jpg", "wb") as fp:
    fp.write(response.read())

你可能感兴趣的:(爬虫)