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
  5. Darkstill777

    Darkstill777 Peon

    Messages:
    1
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #5
    It looks like you're facing a ModuleNotFoundError for the googleads library, even though you believe everything has been installed correctly. Let's troubleshoot this issue step by step:

    1. Check Python Environment: Ensure that the Python environment used by Visual Studio Code is the same one where googleads was installed. Sometimes, Visual Studio Code might be configured to use a different Python interpreter than the one used for installation.

    2. Reinstall the Module: Try reinstalling the googleads module. Open the terminal in Visual Studio Code and run:

      bash
      pip install googleads

      Alternatively, if you are using a specific Python interpreter, specify it directly:

      bash
      /path/to/interpreter/python -m pip install googleads

    3. Verify Installation: After installation, you can verify that the module is installed with the correct interpreter by running:

      bash
      /path/to/interpreter/python -m pip list

    4. Restart Visual Studio Code: Sometimes, restarting Visual Studio Code helps in recognizing newly installed packages.

    5. Check for Deprecation: As of my last update, googleads is deprecated and replaced by google-ads. If issues persist, consider transitioning to the newer google-ads library. Install it using:

      bash
      pip install google-ads

      You would need to adjust your script for any changes in the library API.
    If after these steps the problem persists, there might be an issue with your script configuration or other dependencies. Here is the revised portion of your script with a slight modification to ensure the locale setting does not cause issues, and standardized class naming conventions:

    python
    import googleads
    import pandas as pd
    import traceback
    from googleads import adwords
    from googleads import oauth2

    import locale
    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

    For more details, visit: Devox Software
     
    Darkstill777, Apr 30, 2024 IP
  6. Fomin Alex

    Fomin Alex Greenhorn

    Messages:
    62
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    8
    #6
    The error you're encountering, ModuleNotFoundError: No module named google ads, suggests that the Python module google ads is not installed in your Python environment. To fix this issue, you need to make sure that the google ads module is installed. You can install it using pip, the Python package installer, by running the following command in your terminal or command prompt: Copy code pip install google ads Once you've installed the google ads module, try running your script again. It should resolve the ModuleNotFoundError issue. If you're still facing issues after installing the google ads module, ensure that you're using the correct Python environment in Visual Studio Code. Sometimes, if you have multiple Python environments installed, Visual Studio Code might be using a different environment where google ads is not installed. You can select the correct Python interpreter by clicking on the Python version in the bottom-left corner of Visual Studio Code and choosing the appropriate one.
     
    Fomin Alex, May 16, 2024 IP