簡體   English   中英

python從url保存圖像

[英]python save image from url

當我使用 python 通過 urllib2 請求或 urllib.urlretrieve 從 url 保存圖像時遇到問題。 那就是圖片的url是有效的。 我可以使用資源管理器手動下載它。 但是,當我使用python下載圖像時,無法打開文件。 我使用 Mac OS 預覽來查看圖像。 謝謝!

更新:

代碼如下

def downloadImage(self):
    request = urllib2.Request(self.url)
    pic = urllib2.urlopen(request)
    print "downloading: " + self.url
    print self.fileName
    filePath = localSaveRoot + self.catalog  + self.fileName + Picture.postfix
    # urllib.urlretrieve(self.url, filePath)
    with open(filePath, 'wb') as localFile:
        localFile.write(pic.read())

我要下載的圖片網址是http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg

這個 URL 是有效的,我可以通過瀏覽器保存它,但是 python 代碼會下載一個無法打開的文件。 預覽顯示“它可能已損壞或使用了預覽無法識別的文件格式。” 我比較了通過 Python 下載的圖像和通過瀏覽器手動下載的圖像。 前者的大小要小幾個字節。 所以看起來文件是未完成的,但我不知道為什么python不能完全下載它。

import requests

img_data = requests.get(image_url).content
with open('image_name.jpg', 'wb') as handler:
    handler.write(img_data)

在 Windows 上適用於我的示例代碼:

import requests

with open('pic1.jpg', 'wb') as handle:
    response = requests.get(pic_url, stream=True)

    if not response.ok:
        print(response)

    for block in response.iter_content(1024):
        if not block:
            break

        handle.write(block)

這是使用urlib.request包從 Internet 下載和保存圖像的最簡單方法。

在這里,您可以簡單地傳遞圖像 URL(從您要下載並保存圖像的位置)和目錄(您要在本地保存下載圖像的位置,並以 .jpg 或 .png 給出圖像名稱)這里我給出了“ local-filename.jpg" 替換為這個。

蟒蛇 3

import urllib.request
imgURL = "http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg"

urllib.request.urlretrieve(imgURL, "D:/abc/image/local-filename.jpg")

如果您擁有來自 Internet 的所有圖像 URL,您也可以下載多個圖像。 只需在 for 循環中傳遞這些圖像 URL,代碼就會自動從 Internet 下載圖像。

用於從 url 下載文件並使用其名稱保存的 Python 代碼片段

import requests

url = 'http://google.com/favicon.ico'
filename = url.split('/')[-1]
r = requests.get(url, allow_redirects=True)
open(filename, 'wb').write(r.content)
import random
import urllib.request

def download_image(url):
    name = random.randrange(1,100)
    fullname = str(name)+".jpg"
    urllib.request.urlretrieve(url,fullname)     
download_image("http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg")

我在使用python通過urllib2請求或urllib.urlretrieve從url保存圖像時遇到問題。 那就是圖像的URL是有效的。 我可以使用資源管理器手動下載它。 但是,當我使用python下載圖像時,無法打開該文件。 我使用Mac OS預覽來查看圖像。 謝謝!

更新:

代碼如下

def downloadImage(self):
    request = urllib2.Request(self.url)
    pic = urllib2.urlopen(request)
    print "downloading: " + self.url
    print self.fileName
    filePath = localSaveRoot + self.catalog  + self.fileName + Picture.postfix
    # urllib.urlretrieve(self.url, filePath)
    with open(filePath, 'wb') as localFile:
        localFile.write(pic.read())

我要下載的圖像URL是http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg

這個網址是有效的,我可以通過瀏覽器保存它,但是python代碼會下載無法打開的文件。 預覽顯示“它可能已損壞或使用了預覽無法識別的文件格式。” 我比較了我通過Python下載的圖像和通過瀏覽器手動下載的圖像。 前者的大小要小幾個字節。 因此,似乎文件未完成,但是我不知道為什么python無法完全下載它。

我在使用python通過urllib2請求或urllib.urlretrieve從url保存圖像時遇到問題。 那就是圖像的URL是有效的。 我可以使用資源管理器手動下載它。 但是,當我使用python下載圖像時,無法打開該文件。 我使用Mac OS預覽來查看圖像。 謝謝!

更新:

代碼如下

def downloadImage(self):
    request = urllib2.Request(self.url)
    pic = urllib2.urlopen(request)
    print "downloading: " + self.url
    print self.fileName
    filePath = localSaveRoot + self.catalog  + self.fileName + Picture.postfix
    # urllib.urlretrieve(self.url, filePath)
    with open(filePath, 'wb') as localFile:
        localFile.write(pic.read())

我要下載的圖像URL是http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg

這個網址是有效的,我可以通過瀏覽器保存它,但是python代碼會下載無法打開的文件。 預覽顯示“它可能已損壞或使用了預覽無法識別的文件格式。” 我比較了我通過Python下載的圖像和通過瀏覽器手動下載的圖像。 前者的大小要小幾個字節。 因此,似乎文件未完成,但是我不知道為什么python無法完全下載它。

任何想知道如何獲取圖像擴展名的人都可以嘗試在圖像 url 上使用字符串拆分方法:

str_arr = str(img_url).split('.')
img_ext = '.' + str_arr[3] #www.bigbasket.com/patanjali-atta.jpg (jpg is after 3rd dot so)
img_data = requests.get(img_url).content
with open(img_name + img_ext, 'wb') as handler:
    handler.write(img_data)

下載圖片並保存到目錄

import requests

headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0",
           "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
           "Accept-Language": "en-US,en;q=0.9"
           }

img_data = requests.get(url=image_url, headers=headers).content
with open(create_dir() + "/" + 'image_name' + '.png', 'wb') as handler:
    handler.write(img_data)

用於創建目錄

def create_dir():
    # Directory
    dir_ = "CountryFlags"
    # Parent Directory path
    parent_dir = os.path.dirname(os.path.realpath(__file__))
    # Path
    path = os.path.join(parent_dir, dir_)
    os.mkdir(path)
    return path

對於 linux 以防萬一; 你可以使用 wget 命令

import os
url1 = 'YOUR_URL_WHATEVER'
os.system('wget {}'.format(url1))

您可以從 Google 圖片中選擇任意圖片,復制 url,然后使用以下方法下載圖片。 請注意,擴展名並不總是包含在 url 中,正如其他一些答案似乎假設的那樣。 您可以使用 Python 3.9 中包含的 imghdr 自動檢測正確的擴展名。

import requests, imghdr

gif_url = 'https://media.tenor.com/images/eff22afc2220e9df92a7aa2f53948f9f/tenor.gif'
img_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwXRq7zbWry0MyqWq1Rbq12g_oL-uOoxo4Yw&usqp=CAU'
for url, save_basename in [
    (gif_url, 'gif_download_test'),
    (img_url, 'img_download_test')
]:
    response = requests.get(url)
    if response.status_code != 200:
        raise URLError
    extension = imghdr.what(file=None, h=response.content)
    save_path = f"{save_basename}.{extension}"
    with open(save_path, 'wb') as f:
        f.write(response.content)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM