Posts tagged with python-3.x

I am using Python version 3.7.7, Trying to run to code for 'ads_service.search'. That gave me the error that 'Specified Google Ads API version "v3" does not exist'

import argparse import sys import google.ads.google_ads.client ADS_PAGE_SIZE = 1000 def main(client, customer_id):   ads_service = client.get_service('GoogleAdsService', version='v3')   query = ('SELECT change_status.resource_name, '            'change_status.last_change_date_time, '            'change_status.resource_type, '            'change_status.campaign, '            'change_status.ad_group, '            'change_status.resource_status, '            'change_status.ad_group_ad, '            'change_status.ad_group_criterion, '            'change_status.campaign_criterion '            'FROM change_status '            'WHERE change_status.last_change_date_time DURING YESTERDAY '            'ORDER BY change_status.last_change_date_time')   response = ads_service.search(customer_id, query=query,                                 page_size=ADS_PAGE_SIZE) 

I am very new to Python and Stackoverflow. I am working on connecting my Google Ads account with Python to automate few standard charts creation and email them to my team members. Please help me resolve this as I had not been able to find an answer to it upon Googling either. Let me know if I have missed out on any info which might provide more context to the question here.

I have been using the steps as mentioned by @msaniscalchi. Created client ID and client Secret from https://console.developers.google.com and created googleads.yaml file in the same directory as the generate_refresh_token.py. When I run the script with respective client ID and client Secret values, I am getting "invalid syntax" error. I have verified my multiple times my client secret and ID values multiple times.

"""Generates refresh token for AdWords using the Installed Application flow.""" import argparse import sys from google_auth_oauthlib.flow import InstalledAppFlow from oauthlib.oauth2.rfc6749.errors import InvalidGrantError # Your OAuth2 Client ID and Secret. If you do not have an ID and Secret yet, # please go to https://console.developers.google.com and create a set. DEFAULT_CLIENT_ID = 609XXXXXXX22-58mbhXXXXXXXXXXXXXXXXXX6ri.apps.googleusercontent.com DEFAULT_CLIENT_SECRET = 7uO7XXXXXXXXXXXXXX7dKBAP # The AdWords API OAuth2 scope. SCOPE = u'https://www.googleapis.com/auth/adwords' # The redirect URI set for the given Client ID. The redirect URI for Client ID # generated for an installed application will always have this value. _REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob' parser = argparse.ArgumentParser(description='Generates a refresh token with '                                  'the provided credentials.') parser.add_argument('--client_id', default=DEFAULT_CLIENT_ID,                     help='Client Id retrieved from the Developer\'s Console.') parser.add_argument('--client_secret', default=DEFAULT_CLIENT_SECRET,                     help='Client Secret retrieved from the Developer\'s '                     'Console.') parser.add_argument('--additional_scopes', default=None,                     help='Additional scopes to apply when generating the '                     'refresh token. Each scope should be separated by a comma.') class ClientConfigBuilder(object):   """Helper class used to build a client config dict used in the OAuth 2.0 flow.   """   _DEFAULT_AUTH_URI = 'https://accounts.google.com/o/oauth2/auth'   _DEFAULT_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token'   CLIENT_TYPE_WEB = 'web'   CLIENT_TYPE_INSTALLED_APP = 'installed'   def __init__(self, client_type=None, client_id=None, client_secret=None,                auth_uri=_DEFAULT_AUTH_URI, token_uri=_DEFAULT_TOKEN_URI):     self.client_type = client_type     self.client_id = client_id     self.client_secret = client_secret     self.auth_uri = auth_uri     self.token_uri = token_uri   def Build(self):     """Builds a client config dictionary used in the OAuth 2.0 flow."""     if all((self.client_type, self.client_id, self.client_secret,             self.auth_uri, self.token_uri)):       client_config = {           self.client_type: {               'client_id': self.client_id,               'client_secret': self.client_secret,               'auth_uri': self.auth_uri,               'token_uri': self.token_uri           }       }     else:       raise ValueError('Required field is missing.')     return client_config def main(client_id, client_secret, scopes):   """Retrieve and display the access and refresh token."""   client_config = ClientConfigBuilder(       client_type=ClientConfigBuilder.CLIENT_TYPE_WEB, client_id=client_id,       client_secret=client_secret)   flow = InstalledAppFlow.from_client_config(       client_config.Build(), scopes=scopes)   # Note that from_client_config will not produce a flow with the   # redirect_uris (if any) set in the client_config. This must be set   # separately.   flow.redirect_uri = _REDIRECT_URI   auth_url, _ = flow.authorization_url(prompt='consent')   print('Log into the Google Account you use to access your AdWords account '         'and go to the following URL: \n%s\n' % auth_url)   print('After approving the token enter the verification code (if specified).')   code = input('Code: ').strip()   try:     flow.fetch_token(code=code)   except InvalidGrantError as ex:     print('Authentication has failed: %s' % ex)     sys.exit(1)   print('Access token: %s' % flow.credentials.token)   print('Refresh token: %s' % flow.credentials.refresh_token) if __name__ == '__main__':   args = parser.parse_args()   configured_scopes = [SCOPE]   if not (any([args.client_id, DEFAULT_CLIENT_ID]) and           any([args.client_secret, DEFAULT_CLIENT_SECRET])):     raise AttributeError('No client_id or client_secret specified.')   if args.additional_scopes:     configured_scopes.extend(args.additional_scopes.replace(' ', '').split(','))   main(args.client_id, args.client_secret, configured_scopes) 

When I run the above code, I am getting the "Invalid Syntax" error highlighting at the numeric part of the Client ID and Secret.

Syntax error screenshot attached here

Editor Highlighter screenshot attached here

I am trying to access the Google Adwords API, as described in their help-file via following sample code:

from googleads import adwords client = adwords.AdWordsClient.LoadFromStorage() targeting_idea_service = client.GetService('TargetingIdeaService', version='v201809') selector = {'ideaType': 'KEYWORD',            'requestType': 'IDEAS',            'requestedAttributeTypes': ['KEYWORD_TEXT',                                        'SEARCH_VOLUME',                                        'CATEGORY_PRODUCTS_AND_SERVICES'],            'paging': {'startIndex': '0',                       'numberResults': '100'                       },            'searchParameters': [{'xsi_type': 'RelatedToQuerySearchParameter',                                  'queries': ['cats']}]            } page = targeting_idea_service.get(selector) print(page) 

However, when I try to call the API, following error occures:

zeep.exceptions.Fault: [TargetingIdeaError.INVALID_SEARCH_PARAMETERS @ selector.searchParameters.searchParameters[0]; trigger:'RelatedToQuerySearchParameter'] 

Any idea what could cause this error? In my googleads.yaml file (which is called properly, following parameters are set:

# AdWordsClient configurations adwords:   developer_token:    client_id:   client_secret:   refresh_token: 

I have encounter a problem with the google ads report and I have no clue how to fix it... I use the following code to extract the data from google ads via API call

import sys from googleads import adwords import pandas as pd import pandas as np import io output = io.StringIO() def main(client):   # Initialize appropriate service.   report_downloader = client.GetReportDownloader(version='v201809')   # Create report query.   report_query = (adwords.ReportQueryBuilder()                   .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria',                           'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks',                           'Cost')                   .From('CRITERIA_PERFORMANCE_REPORT')                   .Where('Status').In('ENABLED', 'PAUSED')                   .During('LAST_7_DAYS')                   .Build())   # You can provide a file object to write the output to. For this   # demonstration we use sys.stdout to write the report to the screen.   report_downloader.DownloadReportWithAwql(       report_query, 'CSV', output, skip_report_header=False,       skip_column_header=False, skip_report_summary=False,       include_zero_impressions=True)   output.seek(0)   df = pd.read_csv(output)   df = df.to_csv('results.csv') if __name__ == '__main__':   # Initialize client object.   adwords_client = adwords.AdWordsClient.LoadFromStorage()   main(adwords_client) 

the code works as expected and pulls the data and save it in a CSV file, however, when I access the columns it prints just one column 'CRITERIA_PERFORMANCE_REPORT (Nov 5, 2019-Nov 11, 2019)' when I open the csv file looks like this

result.csv

I have tried to drop the first row with df.drop(df.index[0]) to access the rest of the data however nothing seems to be working. is there any way I can remove the first row or change to use the second row as the columns names which is the result I expected.

thanks in advance