|
| 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 | +
|
| 20 | +A basic python command-line example that uses the searchAnalytics.query method |
| 21 | +of the Google Search Console API. This example demonstrates how to query Google |
| 22 | +search results data for your property. Learn more at |
| 23 | +https://developers.google.com/webmaster-tools/ |
| 24 | +
|
| 25 | +To use: |
| 26 | +1) Install the Google Python client library, as shown at https://developers.google.com/webmaster-tools/v3/libraries. |
| 27 | +2) Sign up for a new project in the Google APIs console at https://code.google.com/apis/console. |
| 28 | +3) Register the project to use OAuth2.0 for installed applications. |
| 29 | +4) Copy your client ID, client secret, and redirect URL into the client_secrets.json file included in this package. |
| 30 | +5) Run the app in the command-line as shown below. |
| 31 | +
|
| 32 | +Sample usage: |
| 33 | +
|
| 34 | + $ python search_analytics_api_sample.py 'https://www.example.com/' '2015-05-01' '2015-05-30' |
| 35 | +
|
| 36 | +""" |
| 37 | + |
| 38 | +import argparse |
| 39 | +import sys |
| 40 | +from googleapiclient import sample_tools |
| 41 | + |
| 42 | +# Declare command-line flags. |
| 43 | +argparser = argparse.ArgumentParser(add_help=False) |
| 44 | +argparser.add_argument('property_uri', type=str, |
| 45 | + help=('Site or app URI to query data for (including ' |
| 46 | + 'trailing slash).')) |
| 47 | +argparser.add_argument('start_date', type=str, |
| 48 | + help=('Start date of the requested date range in ' |
| 49 | + 'YYYY-MM-DD format.')) |
| 50 | +argparser.add_argument('end_date', type=str, |
| 51 | + help=('End date of the requested date range in ' |
| 52 | + 'YYYY-MM-DD format.')) |
| 53 | + |
| 54 | + |
| 55 | +def 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 10 pages for the date range, sorted by click count, descending. |
| 91 | + request = { |
| 92 | + 'startDate': flags.start_date, |
| 93 | + 'endDate': flags.end_date, |
| 94 | + 'dimensions': ['page'], |
| 95 | + 'rowLimit': 10 |
| 96 | + } |
| 97 | + response = execute_request(service, flags.property_uri, request) |
| 98 | + print_table(response, 'Top Pages') |
| 99 | + |
| 100 | + # Get the top 10 queries in India, sorted by click count, descending. |
| 101 | + request = { |
| 102 | + 'startDate': flags.start_date, |
| 103 | + 'endDate': flags.end_date, |
| 104 | + 'dimensions': ['query'], |
| 105 | + 'dimensionFilterGroups': [{ |
| 106 | + 'filters': [{ |
| 107 | + 'dimension': 'country', |
| 108 | + 'expression': 'ind' |
| 109 | + }] |
| 110 | + }], |
| 111 | + 'rowLimit': 10 |
| 112 | + } |
| 113 | + response = execute_request(service, flags.property_uri, request) |
| 114 | + print_table(response, 'Top queries in India') |
| 115 | + |
| 116 | + # Group by both country and device. |
| 117 | + request = { |
| 118 | + 'startDate': flags.start_date, |
| 119 | + 'endDate': flags.end_date, |
| 120 | + 'dimensions': ['country', 'device'], |
| 121 | + 'rowLimit': 10 |
| 122 | + } |
| 123 | + response = execute_request(service, flags.property_uri, request) |
| 124 | + print_table(response, 'Group by country and device') |
| 125 | + |
| 126 | + |
| 127 | +def execute_request(service, property_uri, request): |
| 128 | + """Executes a searchAnalytics.query request. |
| 129 | +
|
| 130 | + Args: |
| 131 | + service: The webmasters service to use when executing the query. |
| 132 | + property_uri: The site or app URI to request data for. |
| 133 | + request: The request to be executed. |
| 134 | +
|
| 135 | + Returns: |
| 136 | + An array of response rows. |
| 137 | + """ |
| 138 | + return service.searchanalytics().query( |
| 139 | + siteUrl=property_uri, body=request).execute() |
| 140 | + |
| 141 | + |
| 142 | +def print_table(response, title): |
| 143 | + """Prints out a response table. |
| 144 | +
|
| 145 | + Each row contains key(s), clicks, impressions, CTR, and average position. |
| 146 | +
|
| 147 | + Args: |
| 148 | + response: The server response to be printed as a table. |
| 149 | + title: The title of the table. |
| 150 | + """ |
| 151 | + print title + ':' |
| 152 | + |
| 153 | + if 'rows' not in response: |
| 154 | + print 'Empty response' |
| 155 | + return |
| 156 | + |
| 157 | + rows = response['rows'] |
| 158 | + row_format = '{:<20}' + '{:>20}' * 4 |
| 159 | + print row_format.format('Keys', 'Clicks', 'Impressions', 'CTR', 'Position') |
| 160 | + for row in rows: |
| 161 | + keys = '' |
| 162 | + # Keys are returned only if one or more dimensions are requested. |
| 163 | + if 'keys' in row: |
| 164 | + keys = u','.join(row['keys']).encode('utf-8') |
| 165 | + print row_format.format( |
| 166 | + keys, row['clicks'], row['impressions'], row['ctr'], row['position']) |
| 167 | + |
| 168 | +if __name__ == '__main__': |
| 169 | + main(sys.argv) |
0 commit comments