Google是否有适用于Python的官方Image API?

时间:2010-08-20 21:38:52

标签: python image search

我想使用Python脚本搜索图像并将其从网上删除。这有官方API吗?如果没有API,最好的方法是什么?

2 个答案:

答案 0 :(得分:5)

Google有一个官方API用于访问搜索功能,包括图片。他们使用JSON进行通信,因此可以通过Python轻松访问。它们是许多Python包装器,如this one

答案 1 :(得分:0)

我在Python中使用以下代码搜索Google图像并将图像下载到我的计算机,它使用JSON和FancyURLopener来检索数据:

import os
import sys
import time
from urllib import FancyURLopener
import urllib2
import simplejson

# Define search term
searchTerm = "hello world"

# Replace spaces ' ' in search term for '%20' in order to comply with request
searchTerm = searchTerm.replace(' ','%20')


# Start FancyURLopener with defined version 
class MyOpener(FancyURLopener): 
    version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'
myopener = MyOpener()

# Set count to 0
count= 0

for i in range(0,10):
    # Notice that the start changes for each iteration in order to request a new set of images for each loop
    url = ('https://ajax.googleapis.com/ajax/services/search/images?' + 'v=1.0&q='+searchTerm+'&start='+str(i*4)+'&userip=MyIP')
    print url
    request = urllib2.Request(url, None, {'Referer': 'testing'})
    response = urllib2.urlopen(request)

    # Get results using JSON
    results = simplejson.load(response)
    data = results['responseData']
    dataInfo = data['results']

    # Iterate for each result and get unescaped url
    for myUrl in dataInfo:
        count = count + 1
        print myUrl['unescapedUrl']

        myopener.retrieve(myUrl['unescapedUrl'],str(count)+'.jpg')

    # Sleep for one second to prevent IP blocking from Google
    time.sleep(1)

您还可以找到非常有用的信息here