您好,登錄后才能下訂單哦!
這篇文章主要介紹了python獲取網絡圖片方法及整理過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
方式1
使用urllib庫
import urllib.request import os ,stat url = "https://cn.bing.com/th?id=OHR.Lidong2019_ZH-CN0761273672_1920x1080.jpg" try: urllib.request.urlretrieve(url,filename="/home/baixiaoxu/desk/123.jpg") except IOError as e: print("IOE ERROR") except Exception as e: print("Exception") 注意: 1,獲取地址,判斷地址是否存在 2,本地保存地址,判斷存在 3,獲取遠程地址的圖片名,或改名 """ url = "https://cn.bing.com/th?id=OHR.Lidong2019_ZH-CN0761273672_1920x1080.jpg" file_suffix = os.path.split(url)[1][-20:-1] print(file_suffix) """
2,使用系統庫文件讀寫操作
import urllib.request import os ,stat req = urllib.request.Request(url) file = "/home/baixiaoxu/desk/file-ttttt.jpg" req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.3; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0') response = urllib.request.urlopen(url) html = response.read() with open(file, 'wb') as f: f.write(html)
網上的方法
import os os.makedirs('./image/', exist_ok=True) IMAGE_URL = "https://cache.yisu.com/upload/information/20200622/113/16685.jpg" def urllib_download(): from urllib.request import urlretrieve urlretrieve(IMAGE_URL, './image/img1.png') def request_download(): import requests r = requests.get(IMAGE_URL) with open('./image/img2.png', 'wb') as f: f.write(r.content) def chunk_download(): import requests r = requests.get(IMAGE_URL, stream=True) with open('./image/img3.png', 'wb') as f: for chunk in r.iter_content(chunk_size=32): f.write(chunk)
整理簡單的下載圖片
import urllib from urllib import request import re response = request.urlopen('https://cn.bing.com/') html = response.read() ht = html.decode() pattern = r'bgLink(.*?\.jpg)' compile_re = re.compile(pattern) hh = compile_re.findall(ht) url = hh[0].split('/')[1] download = 'https://cn.bing.com/' + url urllib.request.urlretrieve(download,filename="/home/baixiaoxu/desk/download.jpg")
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。