zoukankan      html  css  js  c++  java
  • google Image search API

    A python client to query image from google. Though the api service has been tagged as (Deprecated), it will work before a new version is released.


    '''
    Loosely based on Mike Verdone's excellent twitter library:
    http://github.com/sixohsix/twitter/


    '''

    from exceptions import Exception
    from urllib import urlencode
    import urllib2

    try:
    import json
    except ImportError:
    import simplejson as json


    class GoogleError(Exception):
    """
    Exception thrown by the search object when there is an
    error interacting with google.com.
    """
    pass

    class GoogleImageSearch(object):
    def __init__(self, endpoint, user_agent= None, cache=None):
    self.endpoint = endpoint
    self.cache = cache
    self.user_agent = user_agent

    def __call__(self, **params):
    params['v']='1.0'
    kwargs = dict(params)
    kwargs = urlencode(kwargs)

    # HTTP GET
    req = urllib2.Request('%s?%s' % (self.endpoint, kwargs))
    print req.get_full_url()
    cache_response = True

    if self.user_agent:
    req.add_header('User-Agent', self.user_agent)

    try:
    handle = urllib2.urlopen(req)
    response = handle.read()
    if cache_response and self.cache != None:
    self.cache.set('googleimagesearch-' + kwargs, response, time=int(time() + 60))
    response = json.loads(response)
    return response
    except urllib2.HTTPError, e:
    raise GoogleError('google imagesearch sent status %i for method: %s\ndetails: %s' % (e.code, e.fp.read()))

    class GoogleImage(GoogleImageSearch):
    def __init__(self, endpoint='https://ajax.googleapis.com/ajax/services/search/images', user_agent='python-googleimage/0.1', cache=None):
    GoogleImageSearch.__init__(self, endpoint=endpoint, user_agent=user_agent, cache=cache)


    if __name__ == '__main__':
    googleimage = GoogleImage()
    query = {'q':'EURECOM'}
    print googleimage(**query)

  • 相关阅读:
    目前博客园NB团队成员名单
    [征询意见]博客园准备组建在线培训团队
    [调查]园子里有哪些朋友在做开源项目
    都是百度惹的祸
    准备成立NBear开源项目团队—博客园NB团队
    [公告]欢迎各地.NET俱乐部负责人与我联系
    [公告]服务器搬迁
    VS 2005 文本编码小技巧
    Net Framework 2.0 事务处理
    ArgoUML 开源UML 建模工具
  • 原文地址:https://www.cnblogs.com/xueliangliu/p/2962163.html
Copyright © 2011-2022 走看看