快速入门:在 Python 中运行 Search Console 应用

此示例 Web 应用会输出您可以访问的网站列表,以及站点地图、 (如果有的话)。

要求

要运行此程序,您需要:

  • 互联网和网络浏览器的访问权限,以便向示例应用授权。
  • Google 账号,其中至少一个网站已在 Google Search Console 中通过验证
  • Python 3 和 flask Web 应用框架。

操作说明

在此示例中,您将调整适用于 Web 服务器应用的 OAuth 2.0 示例 应用。 此示例 Python 应用使用 Flask Web 应用框架来 基于网络的应用,用于管理 OAuth 密钥和调用 Google Cloud API。您 将调整链接的示例以调用 Search Console API,并打印 生成网页。

按照上方链接的 OAuth 示例页面上的设置说明进行操作,并将 示例代码,然后修改代码,如下所示。具体来说,请遵循 针对编码环境、设置(或重复使用)项目的设置说明 可访问 Google Cloud 控制台中的 Search Console API,以及生成凭据 用于 Web 应用。

您将使用完整代码示例 Python 作为此示例的源代码。

请阅读下面的修改,了解您需要对链接到的链接进行哪些更改 操作说明。

如果您需要从 Google App Engine 访问 Google API Python 客户端 则需要使用一个服务账号 以管理您的权限。

修改

按照链接的 OAuth2 示例页面中的说明操作时, 进行如下更改:

  1. 启用 Google Search Console API 而非 Drive API。
  2. 复制上述链接所指向的 OAU 文档末尾的示例应用, 并将这个

    SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
    API_SERVICE_NAME = 'drive'
    API_VERSION = 'v2'
    
    如下所示:
    SCOPES = ['https://www.googleapis.com/auth/webmasters.readonly']
    API_SERVICE_NAME = 'searchconsole'
    API_VERSION = 'v1'
    

  3. 替换 Python 语言的正文 test_api_request() 函数:

    @app.route('/test')
    def test_api_request():
      if 'credentials' not in flask.session:
        return flask.redirect('authorize')
    
      # Load credentials from the session.
      credentials = google.oauth2.credentials.Credentials(
          **flask.session['credentials'])
    
      # Retrieve list of properties in account
      search_console_service = googleapiclient.discovery.build(
          API_SERVICE_NAME, API_VERSION, credentials=credentials)
      site_list = search_console_service.sites().list().execute()
    
      # Filter for verified URL-prefix websites.
      verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
                            if s['permissionLevel'] != 'siteUnverifiedUser'
                            and s['siteUrl'].startswith('http')]
    
      # Print the sitemaps for all websites that you can access.
      results = '<!DOCTYPE html><html><body><table><tr><th>Verified site</th><th>Sitemaps</th></tr>'
      for site_url in verified_sites_urls:
    
        # Retrieve list of sitemaps submitted
        sitemaps = search_console_service.sitemaps().list(siteUrl=site_url).execute()
        results += '<tr><td>%s</td>' % (site_url)
    
        # Add a row with the site and the list of sitemaps
        if 'sitemap' in sitemaps:
          sitemap_list = "<br />".join([s['path'] for s in sitemaps['sitemap']])
        else:
          sitemap_list = "<i>None</i>"
        results += '<td>%s</td></tr>' % (sitemap_list)
    
      results += '</table></body></html>'
    
      # Save credentials back to session in case access token was refreshed.
      # ACTION ITEM: In a production app, you likely want to save these
      #              credentials in a persistent database instead.
      flask.session['credentials'] = credentials_to_dict(credentials)
    
      return results
    

  4. 在测试中,我们需要手动将 OAUTHLIB_INSECURE_TRANSPORT 更改为 1:export OAUTHLIB_INSECURE_TRANSPORT=1。 如果您收到有关运行示例应用所需的 HTTPS 的错误,请尝试设置 变量。