快速入門導覽課程:在 Python 中執行 Search Console 應用程式

這個範例網頁應用程式會輸出可供存取的網站清單,以及每個網站的 Sitemap (如果有的話)。

需求條件

如要執行這個程式,您需要:

  • 連上網際網路和網路瀏覽器,以授權範例應用程式。
  • 擁有至少一個在 Google Search Console 中驗證網站的 Google 帳戶。
  • Python 3 和 flask 網頁應用程式架構。

操作說明

在本範例中,您將調整適用於網路伺服器應用程式的 OAuth 2.0 範例應用程式。這個範例 Python 應用程式範例使用 flask 網頁應用程式架構,執行用於管理 OAuth 金鑰及呼叫 Google Cloud API 的網頁式應用程式。您將調整連結的範例,以呼叫 Search Console API,並輸出網頁中的結果。

按照上方連結的 OAuth 範例頁面上的設定操作說明,複製程式碼範例,然後修改程式碼,如下所示。具體來說,請按照編碼環境設定操作說明,在 Google Cloud 控制台中設定 (或重複使用) 可存取 Search Console API 的專案,然後產生網頁應用程式的憑證。

您將使用 PythonComplete 程式碼範例,做為這個範例的原始碼。

請參閱下方的修改說明,瞭解您需要對連結的操作說明進行哪些變更。

如果要從 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 錯誤,請嘗試設定該變數。