The code samples below provide examples of common targeting functions using the AdWords API. Client Library.
Add targeting criteria to a campaign
#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example adds various types of targeting criteria to a given campaign. To get campaigns, run get_campaigns.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. """ from googleads import adwords CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' # Replace the value below with the ID of a feed that has been configured for # location targeting, meaning it has an ENABLED FeedMapping with criterionType # of 77. Feeds linked to a GMB account automatically have this FeedMapping. # If you don't have such a feed, set this value to None. LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' def main(client, campaign_id, location_feed_id=None): # Initialize appropriate service. campaign_criterion_service = client.GetService( 'CampaignCriterionService', version='v201809') # Create locations. The IDs can be found in the documentation or retrieved # with the LocationCriterionService. california = { 'xsi_type': 'Location', 'id': '21137' } mexico = { 'xsi_type': 'Location', 'id': '2484' } # Create languages. The IDs can be found in the documentation or retrieved # with the ConstantDataService. english = { 'xsi_type': 'Language', 'id': '1000' } spanish = { 'xsi_type': 'Language', 'id': '1003' } # Create a negative campaign criterion operation. negative_campaign_criterion_operand = { 'xsi_type': 'NegativeCampaignCriterion', 'campaignId': campaign_id, 'criterion': { 'xsi_type': 'Keyword', 'matchType': 'BROAD', 'text': 'jupiter cruise' } } criteria = [california, mexico, english, spanish] if location_feed_id: # Distance targeting. Area of 10 miles around targets above. criteria.append({ 'xsi_type': 'LocationGroups', 'feedId': location_feed_id, 'matchingFunction': { 'operator': 'IDENTITY', 'lhsOperand': [{ 'xsi_type': 'LocationExtensionOperand', 'radius': { 'xsi_type': 'ConstantOperand', 'type': 'DOUBLE', 'unit': 'MILES', 'doubleValue': 10 } }] } }) # Create operations operations = [] for criterion in criteria: operations.append({ 'operator': 'ADD', 'operand': { 'campaignId': campaign_id, 'criterion': criterion } }) # Add the negative campaign criterion. operations.append({ 'operator': 'ADD', 'operand': negative_campaign_criterion_operand }) # Make the mutate request. result = campaign_criterion_service.mutate(operations) # Display the resulting campaign criteria. for campaign_criterion in result['value']: print('Campaign criterion with campaign id "%s", criterion id "%s", ' 'and type "%s" was added.' % (campaign_criterion['campaignId'], campaign_criterion['criterion']['id'], campaign_criterion['criterion']['type'])) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID)
Add negative criteria to a customer
#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example adds various types of negative criteria to a customer. These criteria will be applied to all campaigns for the customer. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. """ from googleads import adwords def main(client): # Initialize appropriate service. customer_negative_criterion_service = client.GetService( 'CustomerNegativeCriterionService', version='v201809') criteria = [ # Exclude tragedy & conflict content. { 'xsi_type': 'ContentLabel', 'contentLabelType': 'TRAGEDY' }, # Exclude a specific placement. { 'xsi_type': 'Placement', 'url': 'http://www.example.com' } # Additional criteria types are available for this service. See the types # listed under Criterion here: # https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion ] # Create operations to add each of the criteria above. operations = [{ 'operator': 'ADD', 'operand': { 'criterion': criterion } } for criterion in criteria] # Make the mutate request. result = customer_negative_criterion_service.mutate(operations) # Display the resulting campaign criteria. for negative_criterion in result['value']: print('Customer negative criterion with criterion ID "%s", and type "%s" ' 'was added.' % (negative_criterion['criterion']['id'], negative_criterion['criterion']['type'])) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() main(adwords_client)
Add demographic critera to an ad group
#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example adds demographic criteria to an ad group. To get a list of ad groups, run get_ad_groups.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. """ from googleads import adwords GENDER_MALE = '10' AGE_RANGE_UNDETERMINED = '503999' AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' def main(client, ad_group_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( 'AdGroupCriterionService', version='v201809') # Create the ad group criteria. ad_group_criteria = [ # Targeting criterion. { 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { 'xsi_type': 'Gender', # Create gender criteria. The IDs can be found in the # documentation: # https://developers.google.com/adwords/api/docs/appendix/genders. 'id': GENDER_MALE } }, # Exclusion criterion. { 'xsi_type': 'NegativeAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { 'xsi_type': 'AgeRange', # Create age range criteria. The IDs can be found in the # documentation: # https://developers.google.com/adwords/api/docs/appendix/ages. 'id': AGE_RANGE_UNDETERMINED } } ] # Create operations. operations = [] for criterion in ad_group_criteria: operations.append({ 'operator': 'ADD', 'operand': criterion }) response = ad_group_criterion_service.mutate(operations) if response and response['value']: criteria = response['value'] for ad_group_criterion in criteria: criterion = ad_group_criterion['criterion'] print('Ad group criterion with ad group ID %s, criterion ID %s and ' 'type "%s" was added.' % (ad_group_criterion['adGroupId'], criterion['id'], criterion['type'])) else: print('No criteria were returned.') if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() main(adwords_client, AD_GROUP_ID)
Get all campaign criteria
#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example illustrates how to retrieve all the campaign targets. To set campaign targets, run add_campaign_targeting_criteria.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. """ from googleads import adwords PAGE_SIZE = 500 def main(client): # Initialize appropriate service. campaign_criterion_service = client.GetService( 'CampaignCriterionService', version='v201809') # Construct selector and get all campaign targets. offset = 0 selector = { 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', 'LanguageName', 'LocationName', 'KeywordText'], 'predicates': [{ 'field': 'CriteriaType', 'operator': 'IN', 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] }], 'paging': { 'startIndex': str(offset), 'numberResults': str(PAGE_SIZE) } } more_pages = True while more_pages: page = campaign_criterion_service.get(selector) # Display results. if 'entries' in page: for campaign_criterion in page['entries']: negative = '' if (campaign_criterion['CampaignCriterion.Type'] == 'NegativeCampaignCriterion'): negative = 'Negative ' criterion = campaign_criterion['criterion'] criteria = (criterion['text'] if 'text' in criterion else criterion['platformName'] if 'platformName' in criterion else criterion['name'] if 'name' in criterion else criterion['locationName'] if 'locationName' in criterion else None) print('%sCampaign Criterion found for Campaign ID %s with type %s and ' 'criteria "%s".' % (negative, campaign_criterion['campaignId'], criterion['type'], criteria)) else: print('No campaign targets were found.') offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() main(adwords_client)
Get all targetable languages and carriers
#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Retrieves all languages and carriers available for targeting. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. """ from googleads import adwords def main(client): # Initialize appropriate service. constant_data_service = client.GetService( 'ConstantDataService', version='v201809') # Get all languages. languages = constant_data_service.getLanguageCriterion() # Display results. for language in languages: print('Language with name "%s" and ID "%s" was found.' % (language['name'], language['id'])) # Get all carriers. carriers = constant_data_service.getCarrierCriterion() # Display results. for carrier in carriers: print('Carrier with name "%s", ID "%s", and country code "%s" was ' 'found.' % ( carrier['name'], carrier['id'], getattr(carrier, 'countryCode', 'N/A'))) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() main(adwords_client)
Get location criteria by name
#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example gets all LocationCriterion. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. """ from googleads import adwords def GetLocationString(location): return '%s (%s)' % (location['locationName'], location['displayType'] if 'displayType' in location else None) def main(client): # Initialize appropriate service. location_criterion_service = client.GetService( 'LocationCriterionService', version='v201809') location_names = ['Paris', 'Quebec', 'Spain', 'Deutschland'] # Create the selector. selector = { 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', 'ParentLocations', 'Reach', 'TargetingStatus'], 'predicates': [{ 'field': 'LocationName', 'operator': 'IN', 'values': location_names }, { 'field': 'Locale', 'operator': 'EQUALS', 'values': ['en'] }] } # Make the get request. location_criteria = location_criterion_service.get(selector) # Display the resulting location criteria. for location_criterion in location_criteria: parent_string = '' if ('parentLocations' in location_criterion['location'] and location_criterion['location']['parentLocations']): parent_string = ', '.join([GetLocationString(parent)for parent in location_criterion['location'] ['parentLocations']]) print('The search term "%s" returned the location "%s" of type "%s"' ' with parent locations "%s", reach "%s" and id "%s" (%s)' % (location_criterion['searchTerm'], location_criterion['location']['locationName'], location_criterion['location']['displayType'], parent_string, location_criterion['reach'] if 'reach' in location_criterion else None, location_criterion['location']['id'], location_criterion['location']['targetingStatus'])) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() main(adwords_client)