Python下载图片代码示例

unsplash.com是提供图片资源库的网站,可以用来作封面图等。可以直接使用图片源网址,最好是下载到服务器本地,访问会快点。以下代码执行一次会随机从源地址下载一张图片到指定地址。

# -*- coding: utf-8 -*-
import sys, requests, uuid, hashlib
url = "https://source.unsplash.com/random/800x450"
pic_url = "/Users/test/py3env/" # 要保存的图片的目录
r = requests.get(url=url)   
url = r.url # 获得真实的图片url
status_code = r.status_code

from urllib.parse import urlparse, parse_qs
parseResult = urlparse(url)
param_dict = parse_qs(parseResult.query) # 解析url中的参数和值

fm = param_dict.get('fm')
pic_extname = None # 图片后缀名
if fm:
    pic_extname = fm[0]

if status_code == 200 and pic_extname:
    # 拼成将要保存的文件名
    filename = str(uuid.uuid1()).replace('-', '') + '.' + pic_extname
    full_filename = pic_url + filename
    file_md5 = None # 文件的md5
    with open(full_filename, 'wb') as file:
        file.write(r.content)