一:使用Python中的urllib類中的urlretrieve()函數(shù),直接從網(wǎng)上下載資源到本地,具體代碼:
import os,stat import urllib.request img_url="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1516371301&di=d99af0828bb301fea27c2149a7070" \ "d44&imgtype=jpg&er=1&src=http%3A%2F%2Fupload.qianhuaweb.com%2F2017%2F0718%2F1500369506683.jpg" file_path='D:/book/img' file_name ="pyt" try: #是否有這個路徑 if not os.path.exists(file_path): #創(chuàng)建路徑 os.makedirs(file_path) #獲得圖片后綴 file_suffix = os.path.splitext(img_url)[1] print(file_suffix) #拼接圖片名(包含路徑) filename = '{}{}{}{}'.format(file_path,os.sep,file_name,file_suffix) print(filename) #下載圖片,并保存到文件夾中 urllib.request.urlretrieve(img_url,filename=filename) except IOError as e: print("IOError") except Exception as e: print("Exception")
二:利用讀寫操作寫入文件,具體代碼:
import os,stat import urllib.request for i in range(1,3): if not os.path.exists("./rym"): print("不純在") os.makedirs("./rym") else: print("存在") os.chmod("D:/imagss",777) with urllib.request.urlopen("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1516371301&di=d99af0828b" "b301fea27c2149a7070d44&imgtype=jpg&er=1&src=http%3A%2F%2Fupload.qianhuaweb.com%2F2017%2F0718%" "2F1500369506683.jpg", timeout=30) as response, open("./rym/lyj.png" , 'wb') as f_save: f_save.write(response.read()) f_save.flush() f_save.close() print("成功")
以上所述是小編給大家介紹的Python下載圖片并保存本地的兩種方式詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
