【问题标题】:Querying more properties in Google Search Console via python script通过 python 脚本在 Google Search Console 中查询更多属性
【发布时间】:2016-08-26 07:56:30
【问题描述】:

我正在使用 Python (2.7) 脚本通过 API Google Search Console 数据下载。我想在启动脚本时去掉属性和日期参数:

>python script. py ´http://www.example.com´ ´01-01-2000´ ´01-02-2000´

对于后者,我设法导入 timedelta 并注释掉引用该参数的行:

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).'))
# Start and end dates are commented out as timeframe is dynamically set
'''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.'))'''

now = datetime.datetime.now()   
StartDate = datetime.datetime.now()- timedelta(days=14) 
EndDate = datetime.datetime.now()- timedelta(days=7)

From = StartDate.strftime('%Y-%m-%d' )

To = EndDate.strftime('%Y-%m-%d' ) 

request = {
        'startDate': StartDate.strftime('%Y-%m-%d' ),
        'endDate': EndDate.strftime('%Y-%m-%d' ),
        'dimensions': ['query'],

现在我也想摆脱属性参数,这样我就可以简单地启动脚本并在脚本本身中指定属性。我的最终目标是仅使用一个脚本从多个属性中获取数据。

我尝试重复用于日期的相同程序,但没有运气。不用说我是编码的初学者。

【问题讨论】:

    标签: python python-2.7 google-api google-search-console google-api-python-client


    【解决方案1】:

    我想我可以提供帮助,因为我在使用 google 提供的示例脚本作为指导时遇到了同样的问题。我认为您的代码是从哪个获得的?

    问题在于该脚本使用了 googleapiclient 库中的 sample_tools.py 脚本,该脚本旨在抽象出所有身份验证位,以便您可以轻松地进行快速查询。如果您想修改代码,我建议您从头开始编写。

    这些是我从各种可能对您有用的文档中拼凑而成的函数。

    第 1 阶段:身份验证

    def authenticate_http():
        """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.
      """
        # create flow object
        flow = flow_from_clientsecrets('path to client_secrets.json',
          scope='https://www.googleapis.com/auth/webmasters.readonly',
          redirect_uri='urn:ietf:wg:oauth:2.0:oob')
    
       storage = Storage('credentials_file')
       credentials = storage.get()
       if credentials:
            # print "have auth code"
            http_auth = credentials.authorize(Http())
        else:
            print "need auth code"
            # get authorization server uri
            auth_uri = flow.step1_get_authorize_url()
            print auth_uri
    
            # get credentials object
            code_input = raw_input("Code: ")
            credentials = flow.step2_exchange(code_input)
            storage.put(credentials)
    
            # apply credential headers to all requests
            http_auth = credentials.authorize(Http())
    
        return http_auth
    

    第 2 阶段:构建服务对象

    def build_service(api_name, version):
        # use authenticate_http to return the http object
        http_auth = authenticate_http()
    
        # build gsc service object
        service = build(api_name, version, http=http_auth)
        return service
    

    第 3 阶段:执行请求

    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()
    

    第 4 阶段:Main()

    def main():
        # define service object for the api service you want to use
        gsc_service = build_service('webmasters', 'v3')
    
        # define request
        request = {'request goes here'}
    
        # set your property set string you want to query
        url = 'url or property set string goes here'
    
        # response from executing request
        response = execute_request(gsc_service, url, request)
    
        print response
    

    对于多个属性集,您只需创建一个属性集列表,然后创建一个循环并将每个属性集传递到“execute_request”函数的“url”参数中

    希望这会有所帮助!

    【讨论】:

    • 您使用过什么类型的 Oauth 客户端?网络、手机、Chrome、其他?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    相关资源
    最近更新 更多