python根据txt文件路径,批量下载照片到本地

 单条下载示例

#引用 requests文件
import requests
#下载地址
url='https://xxxxx.xxx.xxx/8.jpg'
name = url.strip().split('/')[-1]
#print(name)
# #把下载地址发送给requests模块
f=requests.get(url)
# #下载文件
with open(name, "wb") as code:
     code.write(f.content)

批量下载示例:

import requests
def download():
        # 读取txt文件
        with open('file_url_text.txt', 'r', encoding='utf8') as file:
            urls = file.readlines()

            # print(urls)
            # 计算链接地址条数
            # n_urls = len(urls)

            # 遍历链接地址下载图片
            for i, url in enumerate(urls):
                try:
                    # header = {'Referer': url}
                    f = requests.get(url.replace('\n', ''))#这里要特别注意,如果下载的照片中只有一张照片是正常的,且是最后一条url地址,加上replace替换换行符即可
                    name = url.strip().split('/')[-1]

                    with open(name, "wb") as code:
                        code.write(f.content)
                    print('%i/%i' % (i, n_urls), 'image')

                except:
                    print('%i/%i' % (i, n_urls), 'no image')
                    print(url)

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

txt地址内容格式:

https://xxxxx.xxx.xxx/1.jpg
https://xxxxx.xxx.xxx/2.jpg
https://xxxxx.xxx.xxx/3.jpg
https://xxxxx.xxx.xxx/4.jpg

你可能感兴趣的:(python,python)