iT邦幫忙

0

1. Python圖片下載方法

Zoey 2019-04-14 18:56:089960 瀏覽

使用python簡單下載圖片的方法

#載入requests套件
import requests
#需要載入os套件,可處理文件和目錄
import os
#創建目錄
os.makedirs('./img/',exist_ok=True)
url='圖片網址'
r=requests.get(url)
with open('./img/圖片名稱','wb') as f:
#將圖片下載下來
    f.write(r.content)

然後就可以確認圖片是否下載下來了~


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

1
ccutmis
iT邦高手 2 級 ‧ 2019-04-15 12:18:52

謝謝分享,我來分享另一種下載方式給網友參考:

import urllib.request,pathlib

url="https://ithelp.ithome.com.tw/storage/image/logo.svg"
dest_dir="C:\myPic\\20190415\\" #存檔資料夾位置
pathlib.Path(dest_dir).mkdir(parents=True, exist_ok=True) 
urllib.request.urlretrieve(url,dest_dir+(url.split("/")[-1:][0]))
print(url.split("/")[-1:][0]+' 下載完成!.')

註: url.split("/")[-1:][0] 取得網址用"/"切割陣列最後一個元素的返回值,
如果url是http..../.../filename.fileExt"形式的就ok ,
如果url是"http..../.../...ooxxaabbccdd"結尾不是檔名格式的,
就可能會下載失敗 或是 下載成功但存成奇怪的名字。
當然這部份也是可以另外寫判斷式避免就是了

我要留言

立即登入留言