1
0

google_kw_test.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. #!/usr/bin/env python
  2. # Copyright 2019 Google LLC
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # https://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """This example generates keyword ideas from a list of seed keywords."""
  16. import argparse
  17. import sys
  18. from google.ads.googleads.client import GoogleAdsClient
  19. from google.ads.googleads.errors import GoogleAdsException
  20. # Location IDs are listed here:
  21. # https://developers.google.com/google-ads/api/reference/data/geotargets
  22. # and they can also be retrieved using the GeoTargetConstantService as shown
  23. # here: https://developers.google.com/google-ads/api/docs/targeting/location-targeting
  24. _DEFAULT_LOCATION_IDS = ["1023191"] # location ID for New York, NY
  25. # A language criterion ID. For example, specify 1000 for English. For more
  26. # information on determining this value, see the below link:
  27. # https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-7
  28. _DEFAULT_LANGUAGE_ID = "1000" # language ID for English
  29. # [START generate_keyword_ideas]
  30. def main(
  31. client, customer_id, location_ids, language_id, keyword_texts, page_url
  32. ):
  33. keyword_plan_idea_service = client.get_service("KeywordPlanIdeaService")
  34. keyword_competition_level_enum = client.get_type(
  35. "KeywordPlanCompetitionLevelEnum"
  36. ).KeywordPlanCompetitionLevel
  37. keyword_plan_network = client.get_type(
  38. "KeywordPlanNetworkEnum"
  39. ).KeywordPlanNetwork.GOOGLE_SEARCH_AND_PARTNERS
  40. location_rns = _map_locations_ids_to_resource_names(client, location_ids)
  41. language_rn = client.get_service(
  42. "LanguageConstantService"
  43. ).language_constant_path(language_id)
  44. # Either keywords or a page_url are required to generate keyword ideas
  45. # so this raises an error if neither are provided.
  46. if not (keyword_texts or page_url):
  47. raise ValueError(
  48. "At least one of keywords or page URL is required, "
  49. "but neither was specified."
  50. )
  51. # Only one of the fields "url_seed", "keyword_seed", or
  52. # "keyword_and_url_seed" can be set on the request, depending on whether
  53. # keywords, a page_url or both were passed to this function.
  54. request = client.get_type("GenerateKeywordIdeasRequest")
  55. request.customer_id = customer_id
  56. request.language = language_rn
  57. request.geo_target_constants = location_rns
  58. request.include_adult_keywords = False
  59. request.keyword_plan_network = keyword_plan_network
  60. # To generate keyword ideas with only a page_url and no keywords we need
  61. # to initialize a UrlSeed object with the page_url as the "url" field.
  62. if not keyword_texts and page_url:
  63. request.url_seed.url = page_url
  64. # To generate keyword ideas with only a list of keywords and no page_url
  65. # we need to initialize a KeywordSeed object and set the "keywords" field
  66. # to be a list of StringValue objects.
  67. if keyword_texts and not page_url:
  68. request.keyword_seed.keywords.extend(keyword_texts)
  69. # To generate keyword ideas using both a list of keywords and a page_url we
  70. # need to initialize a KeywordAndUrlSeed object, setting both the "url" and
  71. # "keywords" fields.
  72. if keyword_texts and page_url:
  73. request.keyword_and_url_seed.url = page_url
  74. request.keyword_and_url_seed.keywords.extend(keyword_texts)
  75. keyword_ideas = keyword_plan_idea_service.generate_keyword_ideas(
  76. request=request
  77. )
  78. for idea in keyword_ideas:
  79. competition_value = idea.keyword_idea_metrics.competition.name
  80. print(
  81. f'Keyword idea text "{idea.text}" has '
  82. f'"{idea.keyword_idea_metrics.avg_monthly_searches}" '
  83. f'average monthly searches and "{competition_value}" '
  84. "competition.\n"
  85. )
  86. # [END generate_keyword_ideas]
  87. def map_keywords_to_string_values(client, keyword_texts):
  88. keyword_protos = []
  89. for keyword in keyword_texts:
  90. string_val = client.get_type("StringValue")
  91. string_val.value = keyword
  92. keyword_protos.append(string_val)
  93. return keyword_protos
  94. def _map_locations_ids_to_resource_names(client, location_ids):
  95. """Converts a list of location IDs to resource names.
  96. Args:
  97. client: an initialized GoogleAdsClient instance.
  98. location_ids: a list of location ID strings.
  99. Returns:
  100. a list of resource name strings using the given location IDs.
  101. """
  102. build_resource_name = client.get_service(
  103. "GeoTargetConstantService"
  104. ).geo_target_constant_path
  105. return [build_resource_name(location_id) for location_id in location_ids]
  106. if __name__ == "__main__":
  107. # GoogleAdsClient will read the google-ads.yaml configuration file in the
  108. # home directory if none is specified.
  109. googleads_client = GoogleAdsClient.load_from_storage(version="v7")
  110. parser = argparse.ArgumentParser(
  111. description="Generates keyword ideas from a list of seed keywords."
  112. )
  113. # The following argument(s) should be provided to run the example.
  114. parser.add_argument(
  115. "-c",
  116. "--customer_id",
  117. type=str,
  118. required=True,
  119. help="The Google Ads customer ID.",
  120. )
  121. parser.add_argument(
  122. "-k",
  123. "--keyword_texts",
  124. nargs="+",
  125. type=str,
  126. required=False,
  127. default=[],
  128. help="Space-delimited list of starter keywords",
  129. )
  130. # To determine the appropriate location IDs, see:
  131. # https://developers.google.com/google-ads/api/reference/data/geotargets
  132. parser.add_argument(
  133. "-l",
  134. "--location_ids",
  135. nargs="+",
  136. type=str,
  137. required=False,
  138. default=_DEFAULT_LOCATION_IDS,
  139. help="Space-delimited list of location criteria IDs",
  140. )
  141. # To determine the appropriate language ID, see:
  142. # https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-7
  143. parser.add_argument(
  144. "-i",
  145. "--language_id",
  146. type=str,
  147. required=False,
  148. default=_DEFAULT_LANGUAGE_ID,
  149. help="The language criterion ID.",
  150. )
  151. # Optional: Specify a URL string related to your business to generate ideas.
  152. parser.add_argument(
  153. "-p",
  154. "--page_url",
  155. type=str,
  156. required=False,
  157. help="A URL string related to your business",
  158. )
  159. args = parser.parse_args()
  160. try:
  161. main(
  162. googleads_client,
  163. args.customer_id,
  164. args.location_ids,
  165. args.language_id,
  166. args.keyword_texts,
  167. args.page_url,
  168. )
  169. except GoogleAdsException as ex:
  170. print(
  171. f'Request with ID "{ex.request_id}" failed with status '
  172. f'"{ex.error.code().name}" and includes the following errors:'
  173. )
  174. for error in ex.failure.errors:
  175. print(f'\tError with message "{error.message}".')
  176. if error.location:
  177. for field_path_element in error.location.field_path_elements:
  178. print(f"\t\tOn field: {field_path_element.field_name}")
  179. sys.exit(1)