Python 2.7 使用Python下载图像

Python 2.7 使用Python下载图像,python-2.7,imagedownload,Python 2.7,Imagedownload,我正在进行一个项目,需要使用python下载一些图像。我试图通过做不同的事情来修复它,但它仍然不起作用。下面是我找到的一些代码,我尝试过使用,但它似乎不起作用。老实说,我是一个编程新手,所以如果能得到一些帮助,我将不胜感激 代码如下: import json import os import time import requests import Image from StringIO import StringIO from requests.exceptions import Connect

我正在进行一个项目,需要使用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')

提前感谢

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

    # Remove file-system path characters from name.
      title = image_info['titleNoFormatting'].replace('/', '').replace('\\', '')
读取错误消息时,我看到该文件不存在(或目录),因为
w
是打开文件的有效模式

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

    title = 'test'

尝试将
标题
硬编码为简单的内容。例如,
title='test'
。感谢您的帮助,我将其更改为test,并进行了迭代以防止图像被覆盖。
    title = 'test'