提问人:Keir Plaice 提问时间:11/4/2023 最后编辑:renzo21Keir Plaice 更新时间:11/5/2023 访问量:37
如何从 Google 的自定义搜索 API 中提取十多个结果?
How can I extract more than ten results from Google's custom search API?
问:
我设法将这段代码组合在一起,将从 Google 自定义搜索引擎返回的 JSON 文件转换为 .csv 文件。它有效。问题是谷歌每页只返回十个结果。
import csv
import json
import requests
url = ('https://www.googleapis.com/customsearch/v1?key=APIKEY&cx=SEARCGENGINEID&q=QUERY&sort=date:r:20231001:20231102')
response = requests.get(url)
response_dict = response.json()
file = open("Testing.csv", "w", newline='')
header = ['Site', 'Title', 'URL', 'Author', 'Date']
writer = csv.writer(file)
writer.writerow(header)
out_rows = 0
for item in response_dict.get('items', []):
title = item.get('title', '')
url = item.get('link', '')
author = item.get('pagemap', {}).get('metatags', [{}])[0].get('author', '')
date = item.get('pagemap', {}).get('metatags', [{}])[0].get('article:published_time', '')
site = item.get('pagemap', {}).get('metatags',[{}])[0].get('og:site_name','')
data = [site, title, url, author, date]
writer.writerow(data)
out_rows += 1
file.close()
print(f"OK! Published file with {out_rows} articles.")
with open("Testing.json", "w") as json_file:
json.dump(response_dict, json_file, indent=2)
您可以通过在 API 请求的 url 中添加 等来访问下一页结果。我想做的,但不知道如何构建它,是让计算机用另一个循环为我做这件事。如果 ,请再次执行该过程,并将其他结果添加到同一工作表中,直到 。最简单的方法是什么?&start=11
&start=21
out_rows=10
out_rows<10
答: 暂无答案
评论