使用Python下载图像

时间:2015-07-06 00:03:17

标签: python-2.7 imagedownload

我正在开发一个项目,我需要使用python下载一些图像。我试图通过做不同的事情来修复它,但它仍然无法正常工作。这是我发现的一些代码,我尝试使用但它似乎不起作用。说实话,我是编程的新手,所以我很乐意得到一些帮助。

以下是代码:

import json
import os
import time
import requests
import Image
from StringIO import StringIO
from requests.exceptions import ConnectionError

def go(query,pathA):

  BASE_URL = 'https://ajax.googleapis.com/ajax/services/search/images?'\
             'v=1.0&q=' + query + '&start=%d'

  BASE_PATH = os.path.join(pathA, query)

  if not os.path.exists(BASE_PATH):
    os.makedirs(BASE_PATH)

  start = 0 
  while start < 60: 
    r = requests.get(BASE_URL % start)
    for image_info in json.loads(r.text)['responseData']['results']:
      url = image_info['unescapedUrl']
      try:
        image_r = requests.get(url)
      except ConnectionError, e:
        print 'could not download %s' % urla
        continue

      # Remove file-system path characters from name.
      title = image_info['titleNoFormatting'].replace('/', '').replace('\\', '')

      fileII = open(os.path.join(BASE_PATH, '%s.jpg') % title, 'w')
      try:
        Image.open(StringIO(image_r.content)).save(fileII, 'JPEG')
      except IOError, e:
        # Throw away some gifs...blegh.
        print 'could not save %s' % url
        continue
      finally:
        fileII.close()

    print start
    start += 4 # 4 images per page.


    time.sleep(1.5)

# Example use
go('landscape', 'myDirectory')

运行上述代码时出现的错误是:

IOError: [Errno 22] invalid mode ('w') or filename: u'myDirectory\landscape\Na
ture - Photo gallery | MIRIADNA.COM.jpg'

提前致谢

1 个答案:

答案 0 :(得分:1)

这段代码定义了保存图像的位置

    # Remove file-system path characters from name.
      title = image_info['titleNoFormatting'].replace('/', '').replace('\\', '')

阅读您的错误消息我看到该文件不存在(或目录),因为w是打开文件的有效模式。

尝试将标题硬编码为简单的本地路径,例如

    title = 'test'
相关问题