2015-04-04 127 views
0

我想從谷歌搜索中提取前50個搜索結果並獲取每個搜索結果的標題和摘錄。 我正在使用以下代碼。使用python搜索谷歌搜索的結果

#!/usr/bin/python3 
import json 
import urllib.request, urllib.parse 

def showsome(searchfor): 
    query = urllib.parse.urlencode({'q': searchfor}) 
    url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query 
    search_response = urllib.request.urlopen(url) 
    search_results = search_response.read().decode("utf8") 
    results = json.loads(search_results) 
    data = results['responseData'] 
    print('Total results: %s' % data['cursor']['estimatedResultCount']) 
    print(data['results']) 
    hits = data['results'] 
    print('Top %d hits:' % len(hits)) 
    print(hits) 

for h in hits: 
    print(' ',h['title']) 
print(' ', h['url']) 

showsome('jaguar') 

但是我只得到4個結果。即圖像搜索之前的結果出現在搜索結果頁面上。 有人可以請建議一個更好的方法來完成這項任務。 它會更好,如果你能給一個基因的方式,可以在其他搜索引擎也可以工作也說yahoo.com

回答

0

如所述here,該API已被棄用。它似乎仍在運作,但我不會依賴它繼續使用。你應該尋找一個替代API。

儘管如此,每個查詢的默認結果數量是4.最小值是1,最大值是8,這可以使用rst查詢參數來設置,即附加&rst=8以獲得每個查詢8個結果。

您需要進行其他查詢才能檢索更多結果。第一個結果是用start查詢參數指定的,例如, &start=4將返回第4次以後的結果。您可以使用results['responseData']['cursor']給你頁碼的映射開始偏移,e.g:

>>> pprint(results['responseData']['cursor']) 
{'currentPageIndex': 0, 
'estimatedResultCount': '29600000', 
'moreResultsUrl': 'http://www.google.com/search?oe=utf8&ie=utf8&source=uds&start=0&hl=en&q=jaguar', 
'pages': [{'label': 1, 'start': '0'}, 
      {'label': 2, 'start': '4'}, 
      {'label': 3, 'start': '8'}, 
      {'label': 4, 'start': '12'}, 
      {'label': 5, 'start': '16'}, 
      {'label': 6, 'start': '20'}, 
      {'label': 7, 'start': '24'}, 
      {'label': 8, 'start': '28'}], 
'resultCount': '29,600,000', 
'searchResultTime': '0.19'} 

詳情可以在鏈接documentation發現,見「標準URL參數」一節。

雅虎的API會有所不同(我預計),所以這種方法將不會在那裏工作。

+0

你能推薦一些其他好的方法來做到這一點嗎? – ronilp 2015-04-04 12:54:44

+0

轉到谷歌和搜索。我發現這個:https://developers.google.com/custom-search/json-api/v1/overview,但我沒有使用它,所以我不能推薦它。有一些討論[這裏](http://stackoverflow.com/q/4082966/21945)。一些人推薦雅虎的API。 – mhawke 2015-04-04 13:06:14