python读取txt并下载URL

知识储备:
strip及split用法
在这里插入图片描述
在这里插入图片描述
字符串格式操作符(%),可实现字符串替换功能。

print('%s is number %d' % ('python',1))

#python is number 1

%s表示由一个字符串来替换,而%d表示由一个整型来替换,另外一个常用的是%f,它表示由一个浮点型来替换。

在这里插入图片描述
在这里插入图片描述

from urllib.request import urlretrieve
import os
# 解决,导入ssl模块,再加一行代码
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

'''
通过txt网址文件,现在图片到本地
'''
def download():    
    categories = ['hello']
    for category in categories:
        # 新建存储hello文件夹存储图片
        # 新建文件夹地址为./data/hello
        os.makedirs('data/%s' % category, exist_ok=True)
        # 读取txt文件
        # txt文件地址为./hello.txt
        with open('%s.txt' % category, 'r') as file:
            urls = file.readlines()
            # 计算URL地址条数
            n_urls = len(urls)
            # 遍历链接地址下载图片
            for i, url in enumerate(urls):
                try:
                     # 请求下载图片,并截取最后链接第一最后一节字段命名图片
                     # 文件命名为./data/hello/000pwF9.jpg
                     urlretrieve(url.strip(), 'data/%s/%s' % (category, url.strip().split('/')[-1]))
                     # hello 1/16
                     print('%s %i/%i' % (category, i, n_urls))
                except:
                	#hello 8/16 no image
                     print('%s %i/%i' % (category, i, n_urls), 'no image')

if __name__ == '__main__':
    download();

成功读取txt中URL,并逐条下载到本地
在这里插入图片描述

参考:
崔庆才教程pdf
简书_python读取txt并下载
SSL:CERTIFICATE_VERIFY_FAILED with urllib
迁移学习_morvanzhou

猜你喜欢

转载自blog.csdn.net/weixin_42610407/article/details/86849464