2014-01-20 128 views
1

對於我的研究項目(社會科學),我想從Google的CSE API中提取特定網站中特定關鍵字的點擊總數。我是「使用」蟒蛇是第一次,我會盡我所能,清楚..如何提取Google自定義搜索API中的搜索結果數量?

import pprint 

from apiclient.discovery import build 

def main(): 
    service = build("customsearch", "v1", 
     developerKey="<my_key>") 
    res = service.cse().list(
    q='greenpeace', 
    cx='<other_key>', 
    siteSearch='www.foe.org', 
    fields='searchInformation' 
    ).execute() 
    pprint.pprint(res) 

if __name__ == '__main__': 
main() 

在我的終端上運行它時,我得到以下結果:

{u'searchInformation': {u'formattedSearchTime': u'0.12', 
        u'formattedTotalResults': u'37', 
        u'searchTime': 0.124824, 
        u'totalResults': u'37'}} 

我如何在這種情況下以變量的形式提取總結果數37?我已經發現如何在csv中保存變量,這是我的最終目標。如果有另一種方法在csv中保存這個號碼,那也沒問題。我將不得不通過從csv中讀取關鍵字和域名並保存其旁邊的點擊總數來執行更多這些搜索......

回答

0

您在res變量中擁有的是Python字典,它的第一個鍵('searchInformation')爲其價值另一個字典,其中你想要的數據是在關鍵'totalResults'

total_results = res['searchInformation']['totalResults'] 
+0

謝謝!然而我得到的是這樣的:name'res'沒有定義 – user3206897

+0

我用'totalRes = res ['searchInformation'] ['totalResults'] ''替換了'pprint.pprint(res)'print totalRes'!這樣做的工作! – user3206897