1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Keyword Planner API with Python

Discussion in 'Google API' started by Francesco Mercuri, Apr 13, 2021.

  1. #1
    Can you help me with this python api request?
    I run the py file on Visual Studio Code and it's telling me

    import googleads
    ModuleNotFoundError: No module named 'googleads'

    but I am sure i pip install everything. Can you check the script?

    import googleads
    import pandas as pd
    import traceback
    from googleads import adwords
    from googleads import oauth2
    
    _locale._getdefaultlocale = (lambda *args: ['en_UK', 'UTF-8'])
    
    class searchVolumePuller():
    def __init__(self,client_ID,client_secret,refresh_token,developer_token,client_customer_id):
    self.client_ID = client_ID
    self.client_secret = client_secret
    self.refresh_token = refresh_token
    self.developer_token = developer_token
    self.client_customer_id = client_customer_id
    
    def get_client(self):
    access_token = oauth2.GoogleRefreshTokenClient(self.client_ID,
    self.client_secret,
    self.refresh_token)
    adwords_client = adwords.AdWordsClient(self.developer_token,
    access_token,
    client_customer_id = self.client_customer_id,
    cache=googleads.common.ZeepServiceProxy.NO_CACHE)
    
    return adwords_client
    
    def get_service(self,service,client):
    
    return client.GetService(service)
    
    def get_search_volume(self,service_client,keyword_list):
    #empty dataframe to append data into and keywords and search volume lists#
    keywords = []
    search_volume = []
    keywords_and_search_volume = pd.DataFrame()
    #need to split data into smaller lists of 700#
    sublists = [keyword_list[x:x+700] for x in range(0,len(keyword_list),700)]
    for sublist in sublists:
    # Construct selector and get keyword stats.
    selector = {
    'ideaType': 'KEYWORD',
    'requestType' : 'STATS'
    }
    
    #select attributes we want to retrieve#
    selector['requestedAttributeTypes'] = [
    'KEYWORD_TEXT',
    'SEARCH_VOLUME'
    ]
    
    #configure selectors paging limit to limit number of results#
    offset = 0
    selector['paging'] = {
    'startIndex' : str(offset),
    'numberResults' : str(len(sublist))
    }
    
    #specify selectors keywords to suggest for#
    selector['searchParameters'] = [{
    'xsi_type' : 'RelatedToQuerySearchParameter',
    'queries' : sublist
    }]
    
    #pull the data#
    page = service_client.get(selector)
    #access json elements to return the suggestions#
    for i in range(0,len(page['entries'])):
    keywords.append(page['entries'][i]['data'][0]['value']['value'])
    search_volume.append(page['entries'][i]['data'][1]['value']['value'])
    
    keywords_and_search_volume['Keywords'] = keywords
    keywords_and_search_volume['Search Volume'] = search_volume
    
    return keywords_and_search_volume
    
    if __name__ == '__main__':
    CLIENT_ID = "my"
    CLIENT_SECRET = "my"
    REFRESH_TOKEN = "my"
    DEVELOPER_TOKEN = "my"
    CLIENT_CUSTOMER_ID = "my"
    
    keyword_list = ['Manchester','Turin','London']
    
    volume_puller = searchVolumePuller(CLIENT_ID,
    CLIENT_SECRET,
    REFRESH_TOKEN,
    DEVELOPER_TOKEN,
    CLIENT_CUSTOMER_ID)
    
    adwords_client = volume_puller.get_client()
    
    
    targeting_service = volume_puller.get_service('TargetingIdeaService', adwords_client)
    
    kw_sv_df = volume_puller.get_search_volume(targeting_service,keyword_list)
    Code (markup):

    Thanks for your time
     
    Francesco Mercuri, Apr 13, 2021 IP
  2. Sabrador

    Sabrador Peon

    Messages:
    1
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #2
    Did it work?

    I want to use it for https://www.dargenta.com
     
    Sabrador, Jan 21, 2022 IP
  3. Ants

    Ants Greenhorn

    Messages:
    8
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #3
    From your post, it appears that you're facing a ModuleNotFoundError for the googleads module when running your script in Visual Studio Code. Let's address some of the issues step by step:

    1. VS Code Environment & Library Installation:
    • The primary issue you're encountering could be due to the Python environment. Ensure that you've installed the googleads library in the Python environment that's running in Visual Studio Code. Sometimes, VS Code might use a different Python interpreter than your system's default.
    • To verify and potentially fix this: pip install googleads
    **Ensure you're running this in the same Python environment that's active in VS Code. You can check which Python interpreter VS Code is using by looking at the bottom-left corner or by accessing the interpreter setting.​

    2. AdWords API Deprecation & Library Clarification:
    • The googleads library interacts with the older AdWords API. However, be aware that the AdWords API has been deprecated in favor of the Google Ads API. For the newer API, you'd use the google-ads library: pip install google-ads
    • If you're starting a new project, or looking to future-proof your current one, consider transitioning to the Google Ads API.
    3. Code Formatting & Structure:
    • There appears to be indentation issues in the code you've provided. Python uses indentation for block structures, so ensure functions, loops, conditionals, etc., are properly indented to avoid syntax errors.
    4. Locale Setting:
    • The line _locale._getdefaultlocale = (lambda *args: ['en_UK', 'UTF-8']) might be unnecessary or cause issues unless you have a specific use-case for it.
    After addressing these points, your script should be on a better footing. If you have further questions, please don't hesitate to ask! Hope this helps!
     
    Ants, Nov 5, 2023 IP
  4. Kuvox

    Kuvox Greenhorn

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #4
    Try to figure out what the most recent version of the Google Ads package is. You'll notice that there are a bunch and older versions and they will still work. All of my more recent ones use google.ads for imports, but I think we mostly use ChatGPT for these API script creations (which has a lagging knowledge base because of the knowledge cut off).

    For example, my imports on one script look like:

    from google.ads.googleads.client import GoogleAdsClient
    from google.ads.googleads.errors import GoogleAdsException

    Try pip installing a few different ones. As far as I can remember there is googleads, google-ads, and others maybe?
     
    Kuvox, Nov 9, 2023 IP