gpt4 book ai didi

python - 如何使用 google customsearch API 查询高级搜索?

转载 作者:太空狗 更新时间:2023-10-29 17:33:06 25 4
gpt4 key购买 nike

如何使用 Google Python 客户端库以编程方式执行 advanced search使用 Google 自定义搜索 API 搜索引擎,以便根据我查询的高级搜索的某些术语和参数返回第一个 n 链接的列表?

我试着检查 documentation (我没有找到任何例子),这个 answer .但是,后者不起作用,因为目前不支持 AJAX API。到目前为止,我试过这个:

from googleapiclient.discovery import build
import pprint

my_cse_id = "test"

def google_search(search_term, api_key, cse_id, **kwargs):
service = build("customsearch", "v1",developerKey="<My developer key>")
res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
return res['items']

results = google_search('dogs', my_api_key, my_cse_id, num=10)

for result in results:
pprint.pprint(result)

还有这个:

import pprint

from googleapiclient.discovery import build


def main():
service = build("customsearch", "v1",developerKey="<My developer key>")

res = service.cse().list(q='dogs').execute()
pprint.pprint(res)

if __name__ == '__main__':
main()

因此,任何关于如何做的想法和advanced search与谷歌的搜索引擎API?。这是我的凭据如何查看谷歌控制台:

credentials

最佳答案

首先,您需要按照 here 所述定义自定义搜索,然后确保您的 my_cse_id 与 google API custom search (cs) id 匹配,例如

cx='017576662512468239146:omuauf_lfve'

是一个搜索引擎,只搜索以 .com 结尾的域。

接下来我们需要我们的 developerKey

from googleapiclient.discovery import build
service = build("customsearch", "v1", developerKey=dev_key)

现在我们可以执行搜索了。

res = service.cse().list(q=search_term, cx=my_cse_id).execute()

我们可以使用 here 中描述的参数添加其他搜索参数,例如语言或国家/地区,例如

res = service.cse().list(q="the best dog food", cx=my_cse_id, cr="countryUK", lr="lang_en").execute()

将用英语搜索“最好的狗粮”,该网站需要来自英国。


以下修改后的代码对我有用。 api_key 已被删除,因为它从未被使用过。

from googleapiclient.discovery import build

my_cse_id = "012156694711735292392:rl7x1k3j0vy"
dev_key = "<Your developer key>"

def google_search(search_term, cse_id, **kwargs):
service = build("customsearch", "v1", developerKey=dev_key)
res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
return res['items']

results = google_search('boxer dogs', my_cse_id, num=10, cr="countryCA", lr="lang_en")
for result in results:
print(result.get('link'))

输出

http://www.aboxerworld.com/whiteboxerfaqs.htm
http://boxerrescueontario.com/?section=available_dogs
http://www.aboxerworld.com/abouttheboxerbreed.htm
http://m.huffpost.com/ca/entry/10992754
http://rawboxers.com/aboutraw.shtml
http://www.tanoakboxers.com/
http://www.mondlichtboxers.com/
http://www.tanoakboxers.com/puppies/
http://www.landosboxers.com/dogs/puppies/puppies.htm
http://www.boxerrescuequebec.com/

关于python - 如何使用 google customsearch API 查询高级搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41032472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com