无法使用动态输入下载图像 python

Cannot download images with dynamic input python

我正在尝试使用 Python 下载图片,我在 Downloading a picture via urllib and 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)

我用过type函数,结果是字符串,不知道为什么不行

编辑:忘记包含变量

你的目标路径是错误的 os.getcwd() 给了你当前的工作目录,而你附加了一个绝对目录。

所以假设您的脚本在 C:\myscript.py 中,os.getcwd() 将 return 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/'