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""" 37 38import argparse 39import sys 40from googleapiclient import sample_tools 41 42# Declare command-line flags. 43argparser = argparse.ArgumentParser(add_help=False) 44argparser.add_argument('property_uri', type=str, 45 help=('Site or app URI to query data for (including ' 46 'trailing slash).')) 47argparser.add_argument('start_date', type=str, 48 help=('Start date of the requested date range in ' 49 'YYYY-MM-DD format.')) 50argparser.add_argument('end_date', type=str, 51 help=('End date of the requested date range in ' 52 'YYYY-MM-DD format.')) 53 54 55def main(argv): 56 service, flags = sample_tools.init( 57 argv, 'webmasters', 'v3', __doc__, __file__, parents=[argparser], 58 scope='https://www.googleapis.com/auth/webmasters.readonly') 59 60 # First run a query to learn which dates we have data for. You should always 61 # check which days in a date range have data before running your main query. 62 # This query shows data for the entire range, grouped and sorted by day, 63 # descending; any days without data will be missing from the results. 64 request = { 65 'startDate': flags.start_date, 66 'endDate': flags.end_date, 67 'dimensions': ['date'] 68 } 69 response = execute_request(service, flags.property_uri, request) 70 print_table(response, 'Available dates') 71 72 # Get totals for the date range. 73 request = { 74 'startDate': flags.start_date, 75 'endDate': flags.end_date 76 } 77 response = execute_request(service, flags.property_uri, request) 78 print_table(response, 'Totals') 79 80 # Get top 10 queries for the date range, sorted by click count, descending. 81 request = { 82 'startDate': flags.start_date, 83 'endDate': flags.end_date, 84 'dimensions': ['query'], 85 'rowLimit': 10 86 } 87 response = execute_request(service, flags.property_uri, request) 88 print_table(response, 'Top Queries') 89 90 # Get top 11-20 mobile queries for the date range, sorted by click count, descending. 91 request = { 92 'startDate': flags.start_date, 93 'endDate': flags.end_date, 94 'dimensions': ['query'], 95 'dimensionFilterGroups': [{ 96 'filters': [{ 97 'dimension': 'device', 98 'expression': 'mobile' 99 }] 100 }], 101 'rowLimit': 10, 102 'startRow': 10 103 } 104 response = execute_request(service, flags.property_uri, request) 105 print_table(response, 'Top 11-20 Mobile Queries') 106 107 # Get top 10 pages for the date range, sorted by click count, descending. 108 request = { 109 'startDate': flags.start_date, 110 'endDate': flags.end_date, 111 'dimensions': ['page'], 112 'rowLimit': 10 113 } 114 response = execute_request(service, flags.property_uri, request) 115 print_table(response, 'Top Pages') 116 117 # Get the top 10 queries in India, sorted by click count, descending. 118 request = { 119 'startDate': flags.start_date, 120 'endDate': flags.end_date, 121 'dimensions': ['query'], 122 'dimensionFilterGroups': [{ 123 'filters': [{ 124 'dimension': 'country', 125 'expression': 'ind' 126 }] 127 }], 128 'rowLimit': 10 129 } 130 response = execute_request(service, flags.property_uri, request) 131 print_table(response, 'Top queries in India') 132 133 # Group by both country and device. 134 request = { 135 'startDate': flags.start_date, 136 'endDate': flags.end_date, 137 'dimensions': ['country', 'device'], 138 'rowLimit': 10 139 } 140 response = execute_request(service, flags.property_uri, request) 141 print_table(response, 'Group by country and device') 142 143 # Group by total number of Search Appearance count. 144 # Note: It is not possible to use searchAppearance with other 145 # dimensions. 146 request = { 147 'startDate': flags.start_date, 148 'endDate': flags.end_date, 149 'dimensions': ['searchAppearance'], 150 'rowLimit': 10 151 } 152 response = execute_request(service, flags.property_uri, request) 153 print_table(response, 'Search Appearance Features') 154 155def execute_request(service, property_uri, request): 156 """Executes a searchAnalytics.query request. 157 158 Args: 159 service: The webmasters service to use when executing the query. 160 property_uri: The site or app URI to request data for. 161 request: The request to be executed. 162 163 Returns: 164 An array of response rows. 165 """ 166 return service.searchanalytics().query( 167 siteUrl=property_uri, body=request).execute() 168 169 170def print_table(response, title): 171 """Prints out a response table. 172 173 Each row contains key(s), clicks, impressions, CTR, and average position. 174 175 Args: 176 response: The server response to be printed as a table. 177 title: The title of the table. 178 """ 179 print '\n --' + title + ':' 180 181 if 'rows' not in response: 182 print 'Empty response' 183 return 184 185 rows = response['rows'] 186 row_format = '{:<20}' + '{:>20}' * 4 187 print row_format.format('Keys', 'Clicks', 'Impressions', 'CTR', 'Position') 188 for row in rows: 189 keys = '' 190 # Keys are returned only if one or more dimensions are requested. 191 if 'keys' in row: 192 keys = u','.join(row['keys']).encode('utf-8') 193 print row_format.format( 194 keys, row['clicks'], row['impressions'], row['ctr'], row['position']) 195 196if __name__ == '__main__': 197 main(sys.argv) 198