此 API 不支持 API 密钥 - Google 搜索控制台错误

MD *_*han 5 google-api oauth-2.0 google-oauth google-search-console

当我尝试获取网站的站点地图但它显示以下错误时:

{'error': {'code': 401, 'message': 'API keys are not supported by this API. Expected OAuth2 access token or other authentication credentials that assert a principal. See https://cloud.google.com/docs/authentication', 'errors': [{'message': 'Login Required.', 'domain': 'global', 'reason': 'required', 'location': 'Authorization', 'locationType': 'header'}], 'status': 'UNAUTHENTICATED', 'details': [{'@type': 'type.googleapis.com/google.rpc.ErrorInfo', 'reason': 'CREDENTIALS_MISSING', 'domain': 'googleapis.com', 'metadata': {'method': 'google.searchconsole.v1.SitemapsService.List', 'service': 'searchconsole.googleapis.com'}}]}}
Run Code Online (Sandbox Code Playgroud)

当我使用 Flask 并在浏览器上运行该项目时,它正在工作。我将访问令牌保留在烧瓶会话中,如谷歌记录的那样。

后来我尝试在没有 Flask 的情况下仅在桌面上运行该应用程序。所以我写了一个桌面的验证码。这是我的新代码,它不起作用:

SCOPES = ['https://www.googleapis.com/auth/webmasters']
API_SERVICE_NAME = 'searchconsole'
API_VERSION = 'v1'
def main():
"""Shows basic usage of the People API.
Prints the name of the first 10 connections.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    YOUR_ACCESS_TOKEN=creds.token
    print(creds.token)
    readSiteMap()
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            CLIENT_SECRETS_FILE, SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.json', 'w') as token:
        token.write(creds.to_json())
        YOUR_ACCESS_TOKEN = creds.token
        readSiteMap()
Run Code Online (Sandbox Code Playgroud)

错误来自于这个方法:

def readSiteMap():
  url="https://searchconsole.googleapis.com/webmasters/v3/sites/"+WEBSITE+"/sitemaps?key="+API_KEY
  token=YOUR_ACCESS_TOKEN
  headers = CaseInsensitiveDict()
  headers["Accept"] = "application/json"
  headers["Authorization"] = "Bearer "+token
  headers["Content-Type"] = "application/json"
  sitemap=requests.get(url=url,headers=headers).json()
  print(sitemap)
  sitemap=sitemap['sitemap'][0]['path']

  xml=requests.get(sitemap).text
  soup=BeautifulSoup(xml,"xml")
  sitemapTags = soup.find_all("sitemap")
  print ("The number of sitemaps are {0}".format(len(sitemapTags)))
  for sitemap in sitemapTags:
    url=sitemap.findNext("loc").text
    if("post" in url):
      sitemaps.append(url)
  print(sitemaps)
Run Code Online (Sandbox Code Playgroud)

请帮我解决这个问题。谢谢