我准备了应该从谷歌网站管理员控制台新的 Web API (v3) 获取数据的代码。
import os
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from apiclient.discovery import build
import googleapiclient
import json
client_email = '<ACCOUNT_IDENTIFIER>@<PROJECT_IDENTIFIER>.iam.gserviceaccount.com'
scopes = ['https://www.googleapis.com/auth/webmasters.readonly',
'https://www.googleapis.com/auth/webmasters']
private_key_path = os.getcwd() + os.path.normpath('/key.p12')
http = httplib2.Http()
credentials = ServiceAccountCredentials.from_p12_keyfile(client_email,
private_key_path,
private_key_password="notasecret",
scopes=scopes
)
http_auth = credentials.authorize(http)
webmasters_service = build('webmasters', 'v3', credentials=credentials, http=http_auth)
query_params = {"startDate": "2016-03-01", "endDate": "2016-03-02"}
try:
quered_results = webmasters_service.searchanalytics().query(
key="<KEY>",
siteUrl="http://<SITE_DOMAIN>/",
body=json.dumps(query_params),
fields="rows",
alt="json"
).execute()
print(quered_results)
except googleapiclient.errors.HttpError as e:
print(e)
执行结果有错误:
<HttpError 500 when requesting https://www.googleapis.com/webmasters/v3/sites/http%3A%2F%2F<SITE_DOMAIN>%2F/searchAnalytics/query?key=<KEY>&alt=json&fields=rows returned "Backend Error"
上面的代码用于使用 p12 格式的 ssh 密钥进行授权。密钥文件正确。使用 client_secrets.json 最终会出现相同的错误,代码。错误的json是:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "backendError",
"message": "Backend Error",
}
],
"code": 500,
"message": "Backend Error"
}
}
- 我确实将电子邮件连接到网站管理员工具控制台。
- 授权似乎有效,因为使用的密钥/帐户没有错误
有任何想法吗?
我注意到当我在https://developers.google.com/apis-explorer上获取“请求正文”设置不正确时会发生同样的错误,但我在发送的 JSON 中没有看到错误。顺便说一句,如果有一些关于此的验证消息会很高兴......