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

时间:2016-05-03 15:51:02

标签: python python-2.7 urllib

我正在尝试使用Python下载图像,我在Downloading a picture via urllib and python中找到了一些很好的答案,但是当我尝试使用easygui输入网址时,图像只是在我的浏览器中打开而不是下载图像

这是我的代码:

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函数,框中的结果是字符串,所以我不知道为什么它不起作用

编辑:忘记包含变量

1 个答案:

答案 0 :(得分:0)

您的目标路径错误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/'