Querying more properties in Google Search Console via python script
<p>I am using a Python (2.7) script to download via API Google Search Console data. I would like to get rid of the property and dates arguments when launching the script:</p>

<pre><code>&gt;python script. py Â´http://www.example.comÂ´ Â´01-01-2000Â´ Â´01-02-2000Â´
</code></pre>

<p>For the latter I managed to do it importing timedelta and commenting out the lines referring to that argument:</p>

<pre><code>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'],
</code></pre>

<p>Now I would like get rid also of the property argument, so that I can simply launch the script and have the property specified in the script itself. My final goal is to get data from several properties using only one script.</p>

<p>I tried to repeat the same procedure used for the dates but no luck. Needless to say I am a total beginner at coding.</p>

<p>I think I can help as I had the same problem when working from the sample script given by google as guidance. Which is what I think you gotten your code from?</p>

<p>The problem is that the script uses the sample_tools.py script in the googleapiclient library, which is meant to abstract away all the authentication bits so you can make a quick query easily. If you want to modify the code, I would recommend writing it from scratch.</p>

<p>These are my functions that I've pieced together from various bits of documentation that you might find useful.</p>

<p>Stage 1: Authentication</p>

<pre><code>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
</code></pre>

<p>Stage 2: Build the Service Object</p>

<pre><code>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
</code></pre>

<p>Stage 3: Execute Request</p>

<pre><code>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()
</code></pre>

<p>Stage 4: Main()</p>

<pre><code>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
</code></pre>

<p>For multiple property sets you can just create a list of property sets, then create a loop and pass each property set into the 'url' argument of the  'execute_request' function</p>

<p>Hope this helps!</p>

python python-2.7 google-api google-webmaster-tools google-api-python-client