1#!/usr/bin/python 2# -*- coding: utf-8 -*- 3# 4# Copyright 2015 Google Inc. All Rights Reserved. 5# 6# Licensed under the Apache License, Version 2.0 (the "License"); 7# you may not use this file except in compliance with the License. 8# You may obtain a copy of the License at 9# 10# http://www.apache.org/licenses/LICENSE-2.0 11# 12# Unless required by applicable law or agreed to in writing, software 13# distributed under the License is distributed on an "AS IS" BASIS, 14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15# See the License for the specific language governing permissions and 16# limitations under the License. 17 18"""Example for using the Google Search Analytics API (part of Search Console API). 19 20A basic python command-line example that uses the searchAnalytics.query method 21of the Google Search Console API. This example demonstrates how to query Google 22search results data for your property. Learn more at 23https://developers.google.com/webmaster-tools/ 24 25To use: 261) Install the Google Python client library, as shown at https://developers.google.com/webmaster-tools/v3/libraries. 272) Sign up for a new project in the Google APIs console at https://code.google.com/apis/console. 283) Register the project to use OAuth2.0 for installed applications. 294) Copy your client ID, client secret, and redirect URL into the client_secrets.json file included in this package. 305) Run the app in the command-line as shown below. 31 32Sample usage: 33 34 $ python search_analytics_api_sample.py 'https://www.example.com/' '2015-05-01' '2015-05-30' 35 36""" 37from __future__ import print_function 38 39import argparse 40import sys 41from googleapiclient import sample_tools 42 43# Declare command-line flags. 44argparser = argparse.ArgumentParser(add_help=False) 45argparser.add_argument('property_uri', type=str, 46 help=('Site or app URI to query data for (including ' 47 'trailing slash).')) 48argparser.add_argument('start_date', type=str, 49 help=('Start date of the requested date range in ' 50 'YYYY-MM-DD format.')) 51argparser.add_argument('end_date', type=str, 52 help=('End date of the requested date range in ' 53 'YYYY-MM-DD format.')) 54 55 56def main(argv): 57 service, flags = sample_tools.init( 58 argv, 'webmasters', 'v3', __doc__, __file__, parents=[argparser], 59 scope='https://www.googleapis.com/auth/webmasters.readonly') 60 61 # First run a query to learn which dates we have data for. You should always 62 # check which days in a date range have data before running your main query. 63 # This query shows data for the entire range, grouped and sorted by day, 64 # descending; any days without data will be missing from the results. 65 request = { 66 'startDate': flags.start_date, 67 'endDate': flags.end_date, 68 'dimensions': ['date'] 69 } 70 response = execute_request(service, flags.property_uri, request) 71 print_table(response, 'Available dates') 72 73 # Get totals for the date range. 74 request = { 75 'startDate': flags.start_date, 76 'endDate': flags.end_date 77 } 78 response = execute_request(service, flags.property_uri, request) 79 print_table(response, 'Totals') 80 81 # Get top 10 queries for the date range, sorted by click count, descending. 82 request = { 83 'startDate': flags.start_date, 84 'endDate': flags.end_date, 85 'dimensions': ['query'], 86 'rowLimit': 10 87 } 88 response = execute_request(service, flags.property_uri, request) 89 print_table(response, 'Top Queries') 90 91 # Get top 11-20 mobile queries for the date range, sorted by click count, descending. 92 request = { 93 'startDate': flags.start_date, 94 'endDate': flags.end_date, 95 'dimensions': ['query'], 96 'dimensionFilterGroups': [{ 97 'filters': [{ 98 'dimension': 'device', 99 'expression': 'mobile' 100 }] 101 }], 102 'rowLimit': 10, 103 'startRow': 10 104 } 105 response = execute_request(service, flags.property_uri, request) 106 print_table(response, 'Top 11-20 Mobile Queries') 107 108 # Get top 10 pages for the date range, sorted by click count, descending. 109 request = { 110 'startDate': flags.start_date, 111 'endDate': flags.end_date, 112 'dimensions': ['page'], 113 'rowLimit': 10 114 } 115 response = execute_request(service, flags.property_uri, request) 116 print_table(response, 'Top Pages') 117 118 # Get the top 10 queries in India, sorted by click count, descending. 119 request = { 120 'startDate': flags.start_date, 121 'endDate': flags.end_date, 122 'dimensions': ['query'], 123 'dimensionFilterGroups': [{ 124 'filters': [{ 125 'dimension': 'country', 126 'expression': 'ind' 127 }] 128 }], 129 'rowLimit': 10 130 } 131 response = execute_request(service, flags.property_uri, request) 132 print_table(response, 'Top queries in India') 133 134 # Group by both country and device. 135 request = { 136 'startDate': flags.start_date, 137 'endDate': flags.end_date, 138 'dimensions': ['country', 'device'], 139 'rowLimit': 10 140 } 141 response = execute_request(service, flags.property_uri, request) 142 print_table(response, 'Group by country and device') 143 144 # Group by total number of Search Appearance count. 145 # Note: It is not possible to use searchAppearance with other 146 # dimensions. 147 request = { 148 'startDate': flags.start_date, 149 'endDate': flags.end_date, 150 'dimensions': ['searchAppearance'], 151 'rowLimit': 10 152 } 153 response = execute_request(service, flags.property_uri, request) 154 print_table(response, 'Search Appearance Features') 155 156def execute_request(service, property_uri, request): 157 """Executes a searchAnalytics.query request. 158 159 Args: 160 service: The webmasters service to use when executing the query. 161 property_uri: The site or app URI to request data for. 162 request: The request to be executed. 163 164 Returns: 165 An array of response rows. 166 """ 167 return service.searchanalytics().query( 168 siteUrl=property_uri, body=request).execute() 169 170 171def print_table(response, title): 172 """Prints out a response table. 173 174 Each row contains key(s), clicks, impressions, CTR, and average position. 175 176 Args: 177 response: The server response to be printed as a table. 178 title: The title of the table. 179 """ 180 print('\n --' + title + ':') 181 182 if 'rows' not in response: 183 print('Empty response') 184 return 185 186 rows = response['rows'] 187 row_format = '{:<20}' + '{:>20}' * 4 188 print(row_format.format('Keys', 'Clicks', 'Impressions', 'CTR', 'Position')) 189 for row in rows: 190 keys = '' 191 # Keys are returned only if one or more dimensions are requested. 192 if 'keys' in row: 193 keys = u','.join(row['keys']).encode('utf-8') 194 print(row_format.format( 195 keys, row['clicks'], row['impressions'], row['ctr'], row['position'])) 196 197if __name__ == '__main__': 198 main(sys.argv) 199