Advertisement
Guest User

Untitled

a guest
Apr 16th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.43 KB | None | 0 0
  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. import csv
  41. from googleapiclient import sample_tools
  42.  
  43. # Declare command-line flags.
  44. argparser = argparse.ArgumentParser(add_help=False)
  45. argparser.add_argument('property_uri', type=str,
  46. help=('Site or app URI to query data for (including '
  47. 'trailing slash).'))
  48. argparser.add_argument('start_date', type=str,
  49. help=('Start date of the requested date range in '
  50. 'YYYY-MM-DD format.'))
  51. argparser.add_argument('end_date', type=str,
  52. help=('End date of the requested date range in '
  53. 'YYYY-MM-DD format.'))
  54.  
  55.  
  56. def 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.  
  145. def execute_request(service, property_uri, request):
  146. """Executes a searchAnalytics.query request.
  147.  
  148. Args:
  149. service: The webmasters service to use when executing the query.
  150. property_uri: The site or app URI to request data for.
  151. request: The request to be executed.
  152.  
  153. Returns:
  154. An array of response rows.
  155. """
  156. return service.searchanalytics().query(
  157. siteUrl=property_uri, body=request).execute()
  158.  
  159.  
  160. def print_table(response, title):
  161. """Prints out a response table.
  162.  
  163. Each row contains key(s), clicks, impressions, CTR, and average position.
  164.  
  165. Args:
  166. response: The server response to be printed as a table.
  167. title: The title of the table.
  168. """
  169. print title + ':'
  170.  
  171. if 'rows' not in response:
  172. print 'Empty response'
  173. return
  174.  
  175. rows = response['rows']
  176. row_format = '{:<20}' + '{:>20}' * 4
  177. print row_format.format('Keys', 'Clicks', 'Impressions', 'CTR', 'Position')
  178. for row in rows:
  179. keys = ''
  180. # Keys are returned only if one or more dimensions are requested.
  181.  
  182. if 'keys' in row:
  183. keys = u','.join(row['keys']).encode('utf-8')
  184. print row_format.format(
  185. keys, row['clicks'], row['impressions'], row['ctr'], row['position'])
  186.  
  187.  
  188. if __name__ == '__main__':
  189. main(sys.argv)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement