Evg
Evg

Reputation: 55

How to get all Google Adwords locations programmatically?

I recently started to use Google Adwords API, and trying to figure out how to load all Google locations(geotargets)? I can see that there is csv file available on their page with all locations - https://developers.google.com/adwords/api/docs/appendix/geotargeting and it gets updated from time to time with newer version, if some changes are made to it. After every update the latest file has different name. Is there a way to get this csv file programmatically using their API? Or if not csv file, then just a list of locations?

By the way, this file has about 100,000 rows, why there are not so many locations in there?

Upvotes: 0

Views: 747

Answers (1)

Vidyadhar
Vidyadhar

Reputation: 135

You can do it through requests-html module of Python.

Workflow will be

  1. Go to https://developers.google.com/google-ads/api/reference/data/geotargets?hl=en
  2. Search for the Latest .csv (YYYY-MM-DD) text. If found load the file.

For reference purpose I am printing the output on screen. You can dump it in csv file for further user.

import csv
from requests_html import HTMLSession
from urllib.parse import urlparse

geotarget_url = 'https://developers.google.com/google-ads/api/reference/data/geotargets?hl=en'

parsed_url = urlparse(geotarget_url)
domain = parsed_url.scheme + "://" + parsed_url.netloc

session = HTMLSession()
try:
    geotarget = session.get(geotarget_url)
    csv_link = geotarget.html.xpath("//*[contains(text(),'Latest')]/@href", first=True)
    csv_url = domain + csv_link
    csv_data = session.get(csv_url)
    decoded_content = csv_data.content.decode('utf-8')
    csv_reader = csv.reader(decoded_content.splitlines(), delimiter=',')
    for row in csv_reder:
        print(row)
except:
    pass

Upvotes: 1

Related Questions