2013-01-04 112 views
0
#! /usr/bin/python 
import pprint 

from apiclient.discovery import build 


def main(): 
    service = build("customsearch", "v1",       
    developerKey="<mykey>") 

    res = service.cse().list(
    q='the.hobbit.2012', 
    cx='<the other key>', 
).execute() 
pprint.pprint(res) 
if __name__ == '__main__': 
main() 

是我運行的代碼和下面是結果我得到:蟒谷歌API獲取特定信息

{u'context': {u'title': u'IMDB Search Engine'}, 
u'items': [{u'cacheId': u'kzgitw0HPeAJ', 
      u'displayLink': u'www.imdb.com', 
      u'formattedUrl': u'www.imdb.com/title/tt0903624/', 
      u'htmlFormattedUrl': u'www.imdb.com/title/tt0903624/', 
      u'htmlSnippet': u'Directed by Peter Jackson. With Martin Freeman, Ian  McKellen, Richard Armitage<br> , Andy Serkis. A younger and more reluctant <b>Hobbit</b>,  Bilbo Baggins, sets out on <b>...</b>', 
      u'htmlTitle': u'<b>The Hobbit</b>: An Unexpected Journey (<b>2012</b>) -  IMDb',  
      u'kind': u'customsearch#result', 
      u'link': u'http://www.imdb.com/title/tt0903624/', 
      u'pagemap': {u'aggregaterating': [{u'bestrating': u'10', 
               u'ratingcount': u'157,307', 
               u'ratingvalue': u'8.4', 
               u'reviewcount': u'855'}], 

現在的問題是,如果我想從u'formattedUrl」 信息我以爲我可以做

urlinfo = res['item']['url']['formattedUrl'] 

像我會這樣做與forexample Objconfig。但那不行。那麼我如何獲得具體的信息呢?有沒有簡單的方法來做到這一點?

回答

1

From Google API Client documentation:「響應從JSON響應建立一個Python對象......」

items的值是一個數組,所以你需要指定要檢索的元素的ID:

urlinfo = res['items'][0]['formattedUrl']