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

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

要求

如需运行此程序,您需要:

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

操作说明

在本示例中,您将改写适用于网络服务器应用的 OAuth 2.0 示例应用。此示例 Python 应用使用 Flask Web 应用框架运行基于 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. 在测试中,我们需要在 Bash 环境中将 OAUTHLIB_INSECURE_TRANSPORT 手动设置为 1:export OAUTHLIB_INSECURE_TRANSPORT=1。如果您遇到运行示例应用所需的 HTTPS 错误,请尝试设置该变量。