本代码解决的场景
有一个会重定向的链接,重定向的链接是一张随机的图片,将该图片下载到本地,循环下载更多的图片
本代码中图片会下载到和py文件相同的目录下
需要安装:pip install requests
代码如下:
import os
import time
import requests
def get_image_url():
url = '会重定向的地址'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
}
print('n正在发起请求...')
try:
response = requests.get(url, headers=headers) # 此处response.url就是重定向地址
check_image(response)
except ConnectionError:
time.sleep(2)
get_image_url()
def check_image(response):
imgName = response.url.split('/')[-1] # 获取图片名
fileList = os.listdir('./') # 获取目录下所有文件名
for fileName in fileList:
if fileName == imgName:
print('n图片重复,重新请求...')
time.sleep(2)
get_image_url() # 重复的图片,跳过
return
down_image(response, imgName)
def down_image(response, imgName):
fileStream = 0
try:
fileStream = requests.get(response.url, stream=True)
except ConnectionError:
print('n请求失败!重新请求...')
time.sleep(2)
get_image_url()
return
print('请求成功,正在下载' + imgName + '...')
with open(imgName, 'wb') as fd:
for chunk in fileStream.iter_content():
fd.write(chunk)
print('下载成功!(停止运行请摁Ctrl + C)')
get_image_url()
if __name__ == '__main__':
get_image_url()
实际运行图:



