我正在尝试搜索多个关键字(在filteredList的列表中)并获取每个搜索结果的列表。这是我在下面尝试过的代码:
from googleapiclient.discovery import build
import csv
import pprint
my_api_key = "xxx"
my_cse_id = "xxx"
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']
filteredList = ['Optimal Elektronika',
'Evrascon',
]
words = [
'vakansiya'
]
newDictList = []
# this is the htmlSnippets, link and also htmlTitle for filtering over the list of the dictionaries
keyValList = ['link', 'htmlTitle', 'htmlSnippet']
for word in filteredList:
results = google_search(word, my_api_key, my_cse_id, num=5)
# print(results)
newDict = dict()
for result in results:
for (key, value) in result.items():
if key in keyValList:
if word in newDict['htmlSnippet']:
pass
newDict[key] = pprint.pprint(value)
newDictList.append(newDict)
print(newDictList)
运行答案脚本
我得到的错误代码(正在运行答案脚本):
Traceback (most recent call last):
File "/Users/valizadavali/PycharmProjects/webScrap/GCS.py", line 39, in <module>
items = google_search(word, API_KEY, CSE_ID, num=5)
File "/Users/valizadavali/PycharmProjects/webScrap/GCS.py", line 11, in google_search
return res['items']
KeyError: 'items'
我没有API密钥来运行此代码,但我看到的错误很少:
使用时
for items in filteredList:
然后您从列表中得到单词,而不是它的索引,因此您无法将其与数字进行比较。
要获取号码,请使用
for items in range(len(filteredList)):
但是最好使用第一个版本,而不要使用此版本,然后使用items
代替]中的[C0
filterd[items]
如果选择带有results = google_search(items, my_api_key, my_cse_id, num=5)
的版本,则不要在项目上加1-因为您会得到range(len(filteredList)):
而不是1..6
的数字,因此跳过了第一个元素0..5
,并且它不会搜索第一个单词。然后,您尝试获取列表中不存在的filteredList[0]
,并且收到错误消息。
filteredList[6]
BTW:您必须在每个循环中创建for word in filteredList:
results = google_search(word, my_api_key, my_cse_id, num=5)
print(results)
newDict = dict()
for result in results:
for (key, value) in result.items():
if key in keyValList:
newDict[key] = value
newDictList.append(newDict)
print(newDictList)
。
BTW:标准newDict = dict()
和print()
仅用于在屏幕上发送文本,并且始终返回pprint.pprint()
,因此您不能将显示的文本分配给变量。如果您必须格式化文本,则为此使用字符串格式。
[EDIT:带有None
的版本,在Python中不是首选。
range(len(...))
编辑:
for index in range(len(filteredList)):
results = google_search(filteredList[index], my_api_key, my_cse_id, num=5)
print(results)
newDict = dict()
for result in results:
for (key, value) in result.items():
if key in keyValList:
newDict[key] = value
newDictList.append(newDict)
print(newDictList)