python urllib 库下载 http文件

直接看demo,运行就可以看到结果:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import urllib


def download_http_source(source_path, output_file):
    try:
        if source_path.startswith("http://") or source_path.startswith("https://"):
            urllib.urlretrieve(source_path, output_file)
            return output_file
        else:
            return ""
    except Exception as e:
        print('download_http_source error %s' % str(e))
        return ""


if __name__ == '__main__':
    source_path = "http://b.hiphotos.baidu.com/image/pic/item/9825bc315c6034a8ef5250cec5134954082376c9.jpg"
    download_file = "test.jpg"
    download_http_source(source_path, download_file)


你可能感兴趣的:(python)