python - 在 googleapiclient 中使用静态变量而不是使用 argparse - Python

标签 python google-search-api

我刚刚开始使用 Google Search Analytics API main sample对于 python 。

我想更进一步,将静态变量传递给sample_tools.init(),而不是在命令行界面中要求它们。

我可以通过什么方式添加这些参数并传递给sample_tools.init()?

start_date = '2015-10-20' start_date = '2015-10-21' var_uri = 'http://www.example.com'

import argparse
import sys
from googleapiclient import sample_tools

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': ['page', 'query'],
        'rowLimit': 50
    }
    response = execute_request(service, flags.property_uri, request)
    print_table(response, 'Top Queries')

最佳答案

这很简单,我只是从数组中删除了 argparser 并将其留空,然后定义变量。

def main(argv):
    service, flags = sample_tools.init(
        argv, 'webmasters', 'v3', __doc__, __file__, parents=[],
        scope='https://www.googleapis.com/auth/webmasters.readonly')

    start_date = datetime.datetime.strftime(
        datetime.datetime.now() - datetime.timedelta(days=4), '%Y-%m-%d')
    end_date = datetime.datetime.strftime(
        datetime.datetime.now() - datetime.timedelta(days=3), '%Y-%m-%d')

    property_uri = 'http://www.bmimedia.net'

    #Create the request. Use the API tutorial to explain how the API works
    request = {
        'startDate': end_date,
        'endDate': end_date,
        'dimensions': ['page', 'query'],
        'rowLimit': 10
    }

    response = execute_request(service, property_uri, request)
    print_table(response, 'Top Queries', end_date)

关于python - 在 googleapiclient 中使用静态变量而不是使用 argparse - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33427357/

相关文章:

python - 我应该使用 .rank 还是 .order_id?

c# - 如何返回准确的谷歌搜索结果?

javascript - 如何忽略 "Unhandled Promise rejection: Template parse errors: ' :gcse:searchbox' is not a known element"

python - 使用 numpy ufuncs 与内置运算符

python - 如何在 vpython 中固定 Canvas 和图形的位置?

python - 如何为flask注册自定义的http状态码?

json - 解析Google自定义搜索API以获取Elasticsearch文档

python - 如何从 GAE 搜索 API 中的 ScoredDocument 返回字段 - Python

python - 根据他们的位置创建一个新列表

python - 类型错误 : object of type 'Response' has no len() [BeautifulSoup]