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

J.D*_*.Do 13 python google-api google-search-api python-3.x google-api-python-client

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

我试图检查文档(我没有找到任何例子),这个答案.但是,后者没有用,因为目前不支持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)
Run Code Online (Sandbox Code Playgroud)

还有这个:

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()
Run Code Online (Sandbox Code Playgroud)

因此,任何关于如何使用谷歌的搜索引擎API进行高级搜索的想法?这就是我的凭据在Google控制台上的显示方式:

证书

Max*_*ers 6

首先,您需要定义此处所述的自定义搜索,然后确保您my_cse_id匹配Google API 自定义搜索(cs)ID,例如

cx='017576662512468239146:omuauf_lfve'
Run Code Online (Sandbox Code Playgroud)

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

接下来我们需要我们developerKey.

from googleapiclient.discovery import build
service = build("customsearch", "v1", developerKey=dev_key)
Run Code Online (Sandbox Code Playgroud)

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

res = service.cse().list(q=search_term, cx=my_cse_id).execute()
Run Code Online (Sandbox Code Playgroud)

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

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

将用英语搜索"最好的狗食",该网站需要来自英国.


以下修改过的代码对我有用.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'))
Run Code Online (Sandbox Code Playgroud)

产量

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/
Run Code Online (Sandbox Code Playgroud)

  • 从文档中:有效值是1到10之间的整数,包括1和10.所有参数均在此处:https://developers.google.com/custom-search/json-api/v1/reference/cse/list (2认同)