2

I am working on a project where I need to download some images using python. I have tried to fix it by doing different things but it is still not working. Here is some code I found and I tried to use but it does not seem to work. To be honest I am a newbie at programming so I would be grateful to get some help.

Here is the code:

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')

The error I get when I run the code above is:

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

Thanks in advance

mhsjlw
  • 322
  • 3
  • 16
MrX
  • 23
  • 3

1 Answers1

1

This bit of code defines where you will save your image

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

Reading your error message I see that file does not exist (or a directory) because w is a valid mode for opening a file.

Try hardcoding the title to a simple and local path, such as

    title = 'test'
Tautvydas
  • 2,027
  • 3
  • 25
  • 38
  • thanks for the help i changed it to test and did an iteration to prevent overwriting of the images. – MrX Jul 06 '15 at 12:01