# This code searches the query from googlecustomsearch api and returns data in json format
import pprint
import json
from googleapiclient.discovery import build
my_api_key = "**************************************"
my_cse_id = "*************************************"
def google_search(search_term, api_key, cse_id, **kwargs):
service = build("customsearch", "v1", developerKey=api_key)
res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
return res['items']
results = google_search(
'Roshan Patel', my_api_key, my_cse_id, num=10)
for result in results:
pprint.pprint(result)
result_dict = json.loads(result)
print result_dict['formattedUrl']
这是我得到的输出:
我想只获取例如:u'formattedUrl'的url部分并将其存储在列表中,该怎么做?
新错误
Traceback (most recent call last):
File "<ipython-input-38-eb898c8de239>", line 1, in <module>
runfile('C:/Users/abc/untitled9.py', wdir='C:/Users/abc')
File "C:\Users\abc\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile
execfile(filename, namespace)
File "C:\Users\abc\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Users/abc/untitled9.py", line 28, in <module>
result_dict = json.loads(result)
File "C:\Users\abc\Anaconda2\lib\json\__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "C:\Users\abc\Anaconda2\lib\json\decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
答案 0 :(得分:1)
你是否需要首先将结果转换为Python对象,比如dict,使用json模块:
result_dict = json.loads(result)
现在你可以过滤你的词典:
result_dict['formattedUrl']
答案 1 :(得分:1)
result
不是JSON,而是实际的Python字典,所以只需:
print result[u'formattedUrl']