用Python错误从Google下载图像?

用Python错误从Google下载图像?,python,image,download,Python,Image,Download,Python新手,我正在尝试从Google自动下载图像。我想输入一个关键字,然后让我的程序自动从谷歌下载/保存图像到一个文件夹中,这样它就可以在我的电脑上使用。这是我的密码: import json import os import time import requests from PIL import Image from StringIO import StringIO from requests.exceptions import ConnectionError def go(que

Python新手,我正在尝试从Google自动下载图像。我想输入一个关键字,然后让我的程序自动从谷歌下载/保存图像到一个文件夹中,这样它就可以在我的电脑上使用。这是我的密码:

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


def go(query, path):

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

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

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

start = 0 # Google's start query string parameter for pagination.
while start < 60: # Google will only return a max of 56 results.
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' % url
    continue

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

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

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


time.sleep(1.5)
我该怎么做才能解决这个问题?请帮忙!我真的很感激

filename: u'... - Desktop Wallpapers |    MIRIADNA..jpg'
                                     ^ This is a problem
Windows不允许在文件名中使用管道字符(
|

发件人:

以下保留字符:

  • <(少于)
  • >(大于)
  • :(冒号)
  • “(双引号)
  • /(正斜杠)
  • \(反斜杠)
  • |(垂直杆或管道)
  • ?(问号)
  • *(星号)
在您的情况下,保留字符出现在您正在下载并随后用于文件名的图片标题中。您可以相当轻松地去除这些字符,例如:

title = ''.join('%s' % lett for lett in [let for let in title if let not in '<>:"/\|?*'])
title='''.join('%s'%lett for lett-in[let for lett-in title if-let-not-in':“/\ \?*”)

但是没有管道字符?但是在代码本身中,我没有包含任何管道字符。当我运行程序时,它返回了一个错误that@user3105664:嗯,如果
image\u info['titlenoformating']
包含Windows不允许在文件名中使用的任何字符,您就有问题了。图像的标题包含保留字符,因此,在形成文件名之前,您需要确保从标题中删除任何这些字符。@您可以在建议中进行编辑吗?谢谢
title = ''.join('%s' % lett for lett in [let for let in title if let not in '<>:"/\|?*'])