【发布时间】:2015-12-14 07:10:20
【问题描述】:
我正在使用以下代码来获取给定域的点击次数、展示次数、点击率和排名。
import argparse
import sys
from googleapiclient import sample_tools
import json
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument('property_uri', type=str,
help=('Site or app URI to query data for (including '
'trailing slash).'))
argparser.add_argument('start_date', type=str,
help=('Start date of the requested date range in '
'YYYY-MM-DD format.'))
argparser.add_argument('end_date', type=str,
help=('End date of the requested date range in '
'YYYY-MM-DD format.'))
def main(argv):
service, flags = sample_tools.init(
argv, 'webmasters', 'v3', __doc__, __file__, parents=[argparser],
scope='https://www.googleapis.com/auth/webmasters.readonly')
request = {
'startDate': flags.start_date,
'endDate': flags.end_date,
'dimensions': ['query'],
'rowLimit': 10
}
response = execute_request(service, flags.property_uri, request)
print json.dumps(response, sort_keys=True, indent=4)
print_table(response, 'Top Queries')
def execute_request(service, property_uri, request):
"""Executes a searchAnalytics.query request.
Args:
service: The webmasters service to use when executing the query.
property_uri: The site or app URI to request data for.
request: The request to be executed.
Returns:
An array of response rows.
"""
return service.searchanalytics().query(
siteUrl=property_uri, body=request).execute()
def print_table(response, title):
"""Prints out a response table.
Each row contains key(s), clicks, impressions, CTR, and average position.
Args:
response: The server response to be printed as a table.
title: The title of the table.
"""
print title + ':'
if 'rows' not in response:
print 'Empty response'
return
rows = response['rows']
row_format = '{:<20}' + '{:>20}' * 4
print row_format.format('Keys', 'Clicks', 'Impressions', 'CTR', 'Position')
for row in rows:
keys = ''
# Keys are returned only if one or more dimensions are requested.
if 'keys' in row:
keys = u','.join(row['keys']).encode('utf-8')
print row_format.format(
keys, row['clicks'], row['impressions'], row['ctr'], row['position'])
if __name__ == '__main__':
main(sys.argv)
当我输入域(如 www.example.de)时,脚本运行良好,该域列在搜索控制台的 Web 界面中。 但是,当我尝试获取另一个站点的值时,该站点未在 Web 界面(可能是 www.example.de/sub_site)中列出,我收到一条错误消息,表明我没有此权限。 (在 Web 界面上,我拥有完全权限并且可以查看值) 问题是,我只需要来自子站点的值。 所以我的问题是,这个功能是在 api 中没有启用还是我的脚本中有错误?
【问题讨论】:
标签: python api google-search-console google-api-python-client