2017-06-13 140 views
-1

以下是我在Python 3中編寫的代碼。這基本上是利用Google Custom Search API。 我似乎無法解決這個問題。任何幫助或指導將不勝感激。TypeError:列表索引必須是整數或切片,而不是str

import urllib 
import urllib.parse 
import urllib.request 
import json 
import sys 
api_key = #key 
url = 'https://www.googleapis.com/customsearch/v1?key=my_key&q=' 
print("Search :") 
search_query = sys.stdin.readline() 
print("Loading...") 
query = urllib.parse.quote(search_query) 
rawData = urllib.request.urlopen(url+query).read() 
jsonData = json.loads(rawData.decode('utf-8')) 
results = jsonData['queries']['request'] 
for i in results: 
    title = results['title'] 
    print(title) 

回答

1

其中之一是一個列表,而不是一本字典:

jsonData 
jsonData['queries'] 
jsonData['queries']['request'] 

檢查日誌,它會告訴你哪一行代碼導致關鍵錯誤。

而且,這樣做無非是打印標題幾次(如果存在的話):

for i in results: 
    title = results['title'] 
    print(title) 
相關問題