如何修改Python代码实现Google Indexing API批量单请求更新5个URL
如何通过批量请求完成多个URL的Google索引更新
你的代码已经具备批量请求的核心逻辑,只需调整几处细节即可实现一次请求完成5个URL的更新,以下是修正后的完整代码:
from oauth2client.service_account import ServiceAccountCredentials from googleapiclient.discovery import build from googleapiclient.http import BatchHttpRequest import httplib2 import json requests = { 'https://test.com/1': 'URL_UPDATED', 'https://test.com/2': 'URL_UPDATED', 'https://test.com/3': 'URL_UPDATED', 'https://test.com/4': 'URL_UPDATED', 'https://test.com/5': 'URL_UPDATED', } JSON_KEY_FILE = "credentials.json" SCOPES = ["https://www.googleapis.com/auth/indexing"] # 授权凭证 credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES) http = credentials.authorize(httplib2.Http()) # 构建服务 service = build('indexing', 'v3', credentials=credentials) def batch_callback(request_id, response, exception): if exception is not None: print(f"请求 {request_id} 出错: {exception}") else: print(f"请求 {request_id} 成功: {response}") # 初始化批量请求,传入全局回调函数 batch = service.new_batch_http_request(callback=batch_callback) # 将每个URL的更新请求添加到批量任务中 for url, update_type in requests.items(): publish_request = service.urlNotifications().publish( body={"url": url, "type": update_type} ) batch.add(publish_request) # 执行批量请求,一次性发送所有任务 batch.execute()
关键调整说明:
- 全局回调函数:初始化
BatchHttpRequest时直接传入回调函数,无需在每个add方法中重复传递,代码更简洁。 - 批量请求打包:通过
batch.add()将5个publish请求全部加入批量任务,最终调用batch.execute()时会将所有请求打包成一个HTTP请求发送,完成一次请求更新5个URL的需求。 - 日志优化:回调函数中增加了请求ID标识,方便区分每个URL的处理结果。
另外注意:oauth2client库已被官方弃用,建议后续迁移到google-auth和google-auth-httplib2库,对应凭证初始化代码可替换为:
from google.oauth2 import service_account credentials = service_account.Credentials.from_service_account_file( JSON_KEY_FILE, scopes=SCOPES )
内容的提问来源于stack exchange,提问作者Ekaterina
相关产品推荐
相关产品推荐

