Python學習筆記31:圖片URL批量轉存到本地


一、數據說明

有幾千張圖片地址,需要下載到本地,數據形式如下:

二、urllib請求方式批量獲取

import os
from urllib import request,error
import requests
import requests


headers = {
    'User_Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'
}

src = 'https://pubfile.xxxxxx.com.cn/'


with open('身份證圖片鏈接.txt','r') as f:
    i = 1
    for path in f:
        url = os.path.join(src,path)
        # image_name = url.strip().split('/')[-1]
        image_name = str(i).zfill(4)+ '.jpg'
        try:
            req = request.Request(url=url, headers= headers)
            response = request.urlopen(req)
            image_path = os.path.join(os.getcwd() + '/images/' + image_name)
            with open(image_path, 'wb') as f:
                f.write(response.read())
        except error.URLError as e:  
            pass
        i += 1
        print('第%s張,save %s to %s sussfully'%(i,image_name,image_path))

結果輸出:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM