urllib中urlparse使用技巧以及iter_content圖片邊下邊存到硬盤使用

import os,requests
from urllib.parse import urlparse

# 如果獲取的鏈接地址如下,但是我們只想要問號前面的怎麼處理
url  = 'http://i2.chuimg.com/657f715d4ba2439e91e9e67f1c7026b9_1125w_1488h.jpg?imageView2/1/w/215/h/136/interlace/1/q/90'
# 以下網址爲多層級目錄情況
# url  = 'https://s.chuimg.com/simpleicons/twitter.svg'
html = urlparse(url)
# ParseResult(scheme='http', netloc='i2.chuimg.com',
# path='/657f715d4ba2439e91e9e67f1c7026b9_1125w_1488h.jpg',
#  params='', query='imageView2/1/w/215/h/136/interlace/1/q/90', fragment='')
print(html)
full_url = '%s://%s%s'%(html.scheme,html.netloc,html.path)
print(full_url) # http://i2.chuimg.com/657f715d4ba2439e91e9e67f1c7026b9_1125w_1488h.jpg
# 圖片名字
file_name = html.path[1:]
print(file_name) # 657f715d4ba2439e91e9e67f1c7026b9_1125w_1488h.jpg
resp = requests.get(full_url)
# 初始化下載圖片目錄
image_dir = os.path.join(os.curdir,'images')
print(image_dir) # .\images
file_path = os.path.join(image_dir,file_name)
print(file_path) # .\images\657f715d4ba2439e91e9e67f1c7026b9_1125w_1488h.jpg
file_menu = os.path.dirname(file_path)
print(file_menu) #去掉文件名,返回目錄 .\images
# makedirs可以創建多級目錄,例如:.\images\simpleicons
# 而mkdir只能創建一級目錄
if not os.path.isdir(file_menu):
    os.makedirs(file_menu)
with open(file_path,'wb')as f:
    # 邊下邊存到硬盤,默認requests是下載到內存中,最後再存到硬盤
    for funk in resp.iter_content(1024):
        f.write(funk)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章