Python读取文本中的图片链接并下载到本地

1.代码

import requests
#下载图片
def download_img(img_url):
#下载图片存储的路径
    path2 = r'D://bak//'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'
    }
    r = requests.get(img_url, headers=headers, stream=True)
    # print(r.status_code) # 返回状态码
    if r.status_code == 200:
        # 截取图片文件名
        img_name = img_url.split('=').pop()
        with open(path2+'./'+img_name, 'wb') as f:
            f.write(r.content)
        return True


if __name__ == '__main__':
    # 读取图片链接文本
    path1 = r'D://bak//000.txt'
    with open(path1, "r") as f:
        for line in f.readlines():
            line = line.strip('\n')  # 去掉列表中每一个元素的换行符
            print(line)
            ret = download_img(line)
            if not ret:
                print("下载失败")
            print("下载成功")

2.文本内容

#000.txt

http://xxxx?accessoryName=xxxxx.jpg
http://xxxxxx?accessoryName=xxxx.jpg

你可能感兴趣的:(python,python,开发语言,后端)