簡體   English   中英

無法使用動態輸入python下載圖像

[英]Cannot download images with dynamic input python

我正在嘗試使用Python下載圖像,並且在通過urllib和python下載圖片時找到了一些不錯的答案,但是當我嘗試使用easygui鍵入url時,圖像只會在瀏覽器中打開,而不是下載圖像

這是我的代碼:

import easygui as eg
import os
import urllib

url = eg.enterbox('Enter url: ', 'URL Choice')
name = eg.enterbox('Enter name: ', 'Name')

def DownloadImage(URL, name):
    try:
        image = urllib.urlopen(URL)
        if image.headers.maintype == 'image':
            buf = image.read()
            path = os.getcwd() + 'C:\Users\USER\ImageGrabber\Pics'
            file_path = '%s%s' % (path,name+'.jpg')
            downloaded_image = file(file_path, 'wb')
            downloaded_image.write(buf)
            image.close()
        else:
            return False
    except:
        print 'Cannot access file'
        return False
    return True

DownloadImage(url,name)

我使用了類型函數,並且框內的結果是字符串,所以我不知道為什么它不起作用

編輯:忘記包含變量

您的目標路徑錯誤os.getcwd()為您提供當前的工作目錄,並且您要追加一個絕對目錄。

因此,假設您的腳本位於C:\\myscript.pyos.getcwd()將返回C:\\並且您要追加到該C:\\Users\\USER\\ImageGrabber\\Pics ,結果將為C:\\C:\\Users\\USER\\ImageGrabber\\Pics這是無效路徑,因此將轉到異常。

path='C:\Users\USER\ImageGrabber\Pics\' 
# The last '\' is important

應該工作

編輯

我無法測試,因為我正在運行linux,但是目錄可能需要像這樣

path='C:/Users/USER/ImageGrabber/Pics/'

暫無
暫無

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

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