如何修复Google Indexing API读取CSV循环提交返回400错误的问题
错误原因
你出现400错误的核心问题是手动拼接JSON请求体时没有正确插入变量,导致提交的JSON格式完全不符合Google API要求:
你写的content = """{ "url": row[0], "type": "URL_UPDATED" }""" 里的row[0]会被当作普通字符串直接放在JSON中,不会被Python解析为你读取到的URL值,同时也没有给URL字段加JSON要求的双引号,最终提交的请求体是非法JSON格式,Google服务器无法解析就会返回400错误。
修复方案
不要手动拼接JSON,直接用Python内置的json模块把字典序列化为合法JSON字符串,完全避免格式错误。修正后的完整代码如下:
from oauth2client.service_account import ServiceAccountCredentials import httplib2 import csv import json # 引入json模块处理序列化 SCOPES = ["https://www.googleapis.com/auth/indexing"] ENDPOINT = "https://indexing.googleapis.com/v3/urlNotifications:publish" # 替换为你自己的服务账号密钥文件路径 JSON_KEY_FILE = "/content/astute-tractor-329613-1baed60ec1c0.json" credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES) http = credentials.authorize(httplib2.Http()) # 打开CSV文件,指定编码避免中文乱码 with open('/content/indekseerida-1.csv', encoding='utf-8') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') # 如果CSV第一行是表头,去掉下面这行的注释跳过表头 # next(readCSV) for row in readCSV: # 跳过空行 if not row: continue current_url = row[0].strip() # 去掉URL前后的空格、换行符 # 用字典构造请求参数,交给json模块转合法JSON字符串 req_body = json.dumps({ "url": current_url, "type": "URL_UPDATED" }) response, content = http.request(ENDPOINT, method="POST", body=req_body) if response.status == 200: print(f'URL {current_url} 提交成功,响应码:{response.status}') else: # 出错时打印返回内容方便排查问题 print(f'URL {current_url} 提交失败,响应码:{response.status},错误信息:{content.decode()}')
额外注意事项
- 确保你的服务账号已经在Google Search Console里被授予了对应站点的所有者/编辑权限,否则就算格式正确也会返回权限类错误
- Google Indexing API有每日提交配额,超出配额也会返回错误,可在Google Cloud控制台查看配额使用情况
内容的提问来源于stack exchange,提问作者Allar
相关产品推荐
相关产品推荐

