Automate Google Ads Search Query Waste with Python: Full Script

Learn how to build a local Python script using the Google Ads API to pull daily search query waste, flag zero-conversion terms, and automate PPC reporting.

By AdTurbo Team · 2026-08-27

Analyzing search terms manually in the Google Ads user interface is one of the biggest productivity bottlenecks for performance marketers. While auditing your queries helps protect your budget, clicking through the UI every morning across multiple campaigns, ad groups, and accounts consumes hours each week.

By building a custom python script google ads api search terms extractor, you can completely automate the identification of non-converting, expensive queries. Running a local script on a daily schedule allows you to extract raw performance data directly from the searchtermview resource, apply mathematical thresholds for wasted spend, and export actionable negative keyword candidates before they drain your quarterly budget.

This technical guide walks through building an end-to-end, production-grade Python script to pull wasted ad spend data with python using the official Google Ads API client library.

---

Why Automating Daily Search Query Waste Detection Matters

Google's shift toward Broad Match and Smart Bidding has made search term monitoring more critical than ever. Search algorithms frequently test semantic variations of your targeted keywords. While this can uncover incremental conversion volume, it also exposes your budget to tangential searches that never convert.

The Limitations of Manual Interface Auditing

Manual auditing via the Google Ads UI introduces several operational vulnerabilities:

1. Latency: Account managers typically check search terms weekly or bi-weekly. A query consuming $25 per day with zero conversions can waste $350 before an auditor notices it.

2. Cognitive Fatigue: Scanning thousands of query rows across multiple client accounts causes auditors to miss low-volume, high-cost bleeders that accumulate across broad match variations.

3. UI Filtering Constraints: The Google Ads web interface makes it difficult to apply multi-factor statistical filters (such as calculating specific cost-per-click anomalies relative to conversion probability across historical cohorts).

The Math of Search Query Waste

In Google Ads, search query waste typically falls into three primary categories:

• Zero-Conversion Bleeders: Queries that accumulate clicks exceeding your break-even cost-per-acquisition (CPA) without recording a conversion.

• Low-Intent Outliers: Queries containing informational modifiers (e.g., free, login, DIY, pdf) that slip through broad or phrase match targeting.

• High-Cost-Per-Click (CPC) Spikes: Queries triggered during auction surges where the cost per click is 3x to 5x higher than your campaign benchmark without delivering commensurate conversion value.

Automating this detection ensures that any query crossing a predetermined loss threshold is immediately flagged for negative keyword addition. If you want a full framework on manual query optimization before scripting, read our search terms report guide.

---

Prerequisites and Google Ads API Authentication Setup

Before writing your Python script, you must configure authentication through the Google Cloud Console and generate API credentials within a Google Ads Manager (MCC) account.

+-----------------------+ +-------------------------+ +----------------------+

| Google Cloud Console | --- | Google Ads Manager (MCC)| --- | google-ads.yaml |

| (OAuth 2.0 Client ID) | | (Developer Token) | | (Local Auth Config) |

+-----------------------+ +-------------------------+ +----------------------+

1. Developer Token and Manager Account

You need a Google Ads Manager Account (MCC) to obtain a developer token.

• Navigate to Tools and Settings API Center in your MCC.

• Request a Developer Token. For testing and local automation against your own accounts, Basic Access or even Test Access is sufficient to query reports.

2. Google Cloud OAuth 2.0 Credentials

• Log in to the Google Cloud Console.

• Create a new project (e.g., ads-waste-automation).

• Enable the Google Ads API in the API Library.

• Go to APIs & Services Credentials and configure an OAuth Consent Screen (set User Type to External or Internal if inside a Google Workspace organization).

• Create an OAuth 2.0 Client ID with the application type set to Desktop Application.

• Download the client secret JSON file.

3. Generating the Refresh Token

The official Google Ads Python repository provides a utility script (authenticateindesktopapplication.py) to generate a permanent refresh token. Run this script locally in your terminal:

bash

python authenticateindesktopapplication.py --clientsecretspath=/path/to/clientsecret.json

Your browser will open, prompting you to grant API access to your Google Ads account. Once completed, the terminal outputs your refreshtoken.

4. Creating the google-ads.yaml Configuration File

Store your credentials in a standard YAML configuration file placed in your home directory (~/google-ads.yaml) or inside your script folder:

yaml

developertoken: "YOURDEVELOPERTOKEN"

clientid: "YOURCLIENTID.apps.googleusercontent.com"

clientsecret: "YOURCLIENTSECRET"

refreshtoken: "1//YOURREFRESHTOKEN"

logincustomerid: "1234567890" Your 10-digit MCC ID without hyphens

useprotoplus: true

Note: If you are querying client accounts under an MCC, logincustomerid must be the ID of the top-level Manager Account.

---

Environment Setup and Dependency Compatibility

Setting up an isolated virtual environment prevents library conflicts between the Google Ads protobuf dependencies and existing Python packages.

Setting Up the Virtual Environment

Execute the following terminal commands to create and activate your environment:

bash

Create directory and virtual environment

mkdir google-ads-waste-monitor

cd google-ads-waste-monitor

python3 -m venv venv

Activate environment

On macOS/Linux:

source venv/bin/activate

On Windows:

venv\Scripts\activate

Required Dependencies

Install the latest version of the Google Ads client library alongside pandas for data structuring:

bash

pip install google-ads pandas python-dotenv

Verify that your Python version is 3.9 or higher, as newer protobuf implementations in google-ads perform best on modern Python runtimes.

---

Constructing the GAQL Query for Search Term Performance

Google Ads uses Google Ads Query Language (GAQL) to fetch reporting data. To inspect search query waste, query the searchtermview resource and join it with campaign and ad group metadata.

sql

SELECT

campaign.id,

campaign.name,

adgroup.id,

adgroup.name,

searchtermview.searchterm,

searchtermview.status,

metrics.clicks,

metrics.impressions,

metrics.costmicros,

metrics.conversions,

metrics.conversionsvalue,

segments.date

FROM searchtermview

WHERE

segments.date DURING LAST7DAYS

AND metrics.clicks 0

ORDER BY metrics.costmicros DESC

GAQL Metrics Breakdown for Waste Identification

| Field | Description | Handling in Python |

| :--- | :--- | :--- |

| searchtermview.searchterm | The exact query entered by the user. | String cleaning and lowercase normalization. |

| metrics.costmicros | Spend represented in micro-units ($1.00 = 1,000,000 micros). | Divide by 1,000,000 to get currency value. |

| metrics.conversions | Number of recorded conversion actions. | Used as primary filter denominator (conversions == 0). |

| metrics.clicks | Total clicks registered for the query. | Used to eliminate low-sample statistical noise. |

| searchtermview.status | Status of the search term (ADDED, EXCLUDED, NONE). | Filter for NONE to find unaddressed waste. |

Understanding these metrics is fundamental to building negative keyword systems. For a broader manual strategy, refer to our guide on how to find negative keywords.

---

Full Python Script: Extracting, Filtering, and Classifying Wasted Spend

The following modular script connects to the API, queries the searchtermview, filters queries that have exceeded a specific spend threshold without yielding a conversion, and exports the data to a timestamped CSV report.

python

import sys

import os

from datetime import datetime

import pandas as pd

from google.ads.googleads.client import GoogleAdsClient

from google.ads.googleads.errors import GoogleAdsException

CONFIGURATION PARAMETERS

CUSTOMERID = "9876543210" Target Client Account ID (no dashes)

YAMLPATH = "google-ads.yaml"

MINCOSTTHRESHOLD = 25.00 Flag search terms spending = $25 with zero conversions

DATERANGE = "LAST7DAYS" Options: TODAY, YESTERDAY, LAST7DAYS, LAST30DAYS

def initclient(configpath: str) - GoogleAdsClient:

"""Initializes and returns the Google Ads API client."""

try:

return GoogleAdsClient.loadfromstorage(configpath)

except Exception as e:

print(f"[ERROR] Failed to load configuration file: {e}")

sys.exit(1)

def fetchsearchterms(client: GoogleAdsClient, customerid: str) - pd.DataFrame:

"""Queries the Google Ads API for search terms and metrics."""

gaservice = client.getservice("GoogleAdsService")

query = f"""

SELECT

campaign.id,

campaign.name,

adgroup.id,

adgroup.name,

searchtermview.searchterm,

searchtermview.status,

metrics.clicks,

metrics.impressions,

metrics.costmicros,

metrics.conversions,

metrics.conversionsvalue

FROM searchtermview

WHERE segments.date DURING {DATERANGE}

AND metrics.clicks 0

ORDER BY metrics.costmicros DESC

"""

records = []

try:

print(f"[INFO] Querying search terms for account {customerid}...")

searchrequest = client.gettype("SearchGoogleAdsStreamRequest")

searchrequest.customerid = customerid

searchrequest.query = query

stream = gaservice.searchstream(searchrequest)

for batch in stream:

for row in batch.results:

cost = row.metrics.costmicros / 1000000.0

records.append({

"campaignid": row.campaign.id,

"campaignname": row.campaign.name,

"adgroupid": row.adgroup.id,

"adgroupname": row.adgroup.name,

"searchterm": row.searchtermview.searchterm,

"status": row.searchtermview.status.name,

"clicks": row.metrics.clicks,

"impressions": row.metrics.impressions,

"cost": cost,

"conversions": row.metrics.conversions,

"conversionvalue": row.metrics.conversionsvalue,

"cpa": cost / row.metrics.conversions if row.metrics.conversions 0 else None

})

except GoogleAdsException as ex:

print(f"[ERROR] Request failed with status {ex.error.code().name}")

for error in ex.failure.errors:

print(f"\tMessage: {error.message}")

if error.location:

for fieldpathelement in error.location.fieldpathelements:

print(f"\t\tOn field: {fieldpathelement.fieldname}")

sys.exit(1)

return pd.DataFrame(records)

def isolatewastedspend(df: pd.DataFrame, costlimit: float) - pd.DataFrame:

"""Filters queries that spent = costlimit with zero conversions."""

if df.empty:

return df

Condition: conversions == 0 and cost = costlimit and status is not already EXCLUDED

wastefilter = (

(df["conversions"] == 0.0) &

(df["cost"] = costlimit) &

(df["status"] != "EXCLUDED")

)

wastedf = df[wastefilter].copy()

wastedf.sortvalues(by="cost", ascending=False, inplace=True)

return wastedf

def main():

client = initclient(YAMLPATH)

dfraw = fetchsearchterms(client, CUSTOMERID)

if dfraw.empty:

print("[INFO] No search term records found for the specified timeframe.")

return

dfwaste = isolatewastedspend(dfraw, MINCOSTTHRESHOLD)

totalspend = dfraw["cost"].sum()

wastedspend = dfwaste["cost"].sum() if not dfwaste.empty else 0.0

wastepercentage = (wastedspend / totalspend 100) if totalspend 0 else 0

print("=" 60)

print("SEARCH TERM WASTE ANALYSIS REPORT")

print("=" 60)

print(f"Total Account Spend: ${totalspend:,.2f}")

print(f"Identified Waste: ${wastedspend:,.2f} ({wastepercentage:.1f}% of total spend)")

print(f"Waste Queries Found: {len(dfwaste)}")

print("=" 60)

if not dfwaste.empty:

timestamp = datetime.now().strftime("%Y%m%d%H%M%S")

outputfilename = f"wastedsearchterms{CUSTOMERID}{timestamp}.csv"

dfwaste.tocsv(outputfilename, index=False)

print(f"[SUCCESS] Wasted queries exported to {outputfilename}")

print("\nTop 5 Most Expensive Wasted Queries:")

print(dfwaste[["searchterm", "campaignname", "cost", "clicks"]].head())

else:

print("[INFO] No search queries exceeded the waste threshold.")

if name == "main":

main()

---

Error Handling, API Quotas, and Production Edge Cases

When deploying a python script google ads api search terms processor in production, scripts must handle API limits, authentication lifecycle issues, and data privacy constraints.

1. Handling API Token Expirations

OAuth 2.0 access tokens expire after 3600 seconds (1 hour). The official google-ads client library handles token refreshes automatically using your refreshtoken. However, if your refresh token is revoked (e.g., due to a password change or consent screen reset), the script will raise an INVALIDGRANT error. Implement a wrapper around the client execution to catch authentication failures and log them to your monitoring dashboard.

2. Google's Search Term Privacy Thresholds

Since late 2020, Google Ads does not return every search query in the API. Queries that do not meet "privacy thresholds" (i.e., searches made by only a few users) appear in aggregate totals inside campaign metrics but are omitted from searchtermview.

Total Campaign Cost ($1,000.00)

├── Explicit Search Terms in API ($750.00) --- [Audited by Script]

└── Hidden Search Query Waste ($250.00) --- [Unmatched Privacy Buffer]

To calculate your account's unidentifiable query spend, calculate the difference between your campaign level cost and the aggregated searchtermview cost:

$\text{Hidden Query Spend} = \text{Total Campaign Cost} - \sum \text{Search Term View Cost}$

If hidden spend exceeds 25-30% of total spend, your broad match expansion may be capturing hyper-long-tail queries that the API will never surface.

3. API Rate Limits and Stream Paging

Using searchstream (as demonstrated in the script above) is vastly superior to search (paged) requests. Streaming pipelines data chunks over a persistent HTTP/2 connection, preventing timeout errors on large accounts with over 100,000 queries per week.

---

Automating Execution via Cron and Webhook Alerts

To turn your one-off script into an automated daily auditor, configure scheduling and alert dispatching.

Scheduling via Linux Cron

Open your crontab editor:

bash

crontab -e

Add the following entry to execute the script daily at 6:00 AM UTC:

cron

0 6 /home/user/google-ads-waste-monitor/venv/bin/python /home/user/google-ads-waste-monitor/extractwaste.py /home/user/google-ads-waste-monitor/cron.log 2&1

Adding Real-Time Slack Webhook Alerts

Instead of merely saving CSVs, you can post flagged search terms directly into your team's Slack channel using Python's urllib or requests library:

python

import json

import urllib.request

def sendslackalert(webhookurl: str, wastedf: pd.DataFrame, totalwaste: float):

"""Sends a summary of wasted queries to a Slack channel via incoming webhook."""

topterms = "\n".join([

f"• {row['searchterm']} (${row['cost']:.2f} across {row['clicks']} clicks)"

for , row in wastedf.head(5).iterrows()

])

payload = {

"text": f":warning: Google Ads Waste Alert\n" \

f"Identified ${totalwaste:,.2f} in non-converting query spend (Last 7 Days).\n\n" \

f"Top Flagged Terms:\n{topterms}"

}

req = urllib.request.Request(

webhookurl,

data=json.dumps(payload).encode("utf-8"),

headers={"Content-Type": "application/json"}

)

urllib.request.urlopen(req)

Integrating this into the main() function ensures that any day a search term breaches your threshold, your team receives an immediate notification to review or negate the query. If you're building a routine audit around this, check our comprehensive PPC audit checklist for related account health metrics.

---

Custom Python Scripts vs. Dedicated Google Ads Automation

While local Python scripts provide complete transparency and zero software subscription fees, maintaining in-house API integrations has trade-offs compared to modern automation tools.

| Dimension | Custom Local Python Scripts | Dedicated Automation Platform |

| :--- | :--- | :--- |

| Cost | Free (excluding dev/maintenance time) | Fixed subscription (e.g., $100–$300/mo) |

| Setup Complexity | High (OAuth, GCP Console, YAML, Python env) | Low (1-Click Google OAuth connect) |

| API Maintenance | High (Google sunsets API versions every 12 months) | Zero (Handled by vendor platform) |

| Actionability | Read-only reporting (or complex write scripts) | Autonomous negative keyword syncing & bid shifts |

| Multi-Account Scale | Requires loop architecture & quota management | Built-in MCC management dashboards |

| Anomaly AI Detection | Limited to hardcoded static rules | Semantic clustering & intent classification |

+-------------------------------------------------------------------------+

| DECISION MATRIX |

| |

| Do you have dedicated Python developers to maintain GAQL changes? |

| ├── YES ── Custom Python Script (Full control, zero software costs) |

| └── NO ── Automation Platform (Fast deployment, managed AI agents) |

+-------------------------------------------------------------------------+

Writing custom code makes sense for technical practitioners managing single accounts with specific reporting needs. However, managing enterprise accounts or multiple clients often requires platforms with automated bid corrections, continuous semantic negative keyword discovery, and multi-channel monitoring.

For performance marketers who want automated waste elimination without writing, debugging, and hosting GAQL scripts, modern solutions like AdTurbo provide complete Google Ads automation starting at $149/month with a 7-day trial (card required). An AI manager continuously analyzes broad match query drift and automatically applies negative keywords 24/7.

---

Advanced Query Classification: Regex and NLP Intent Filtering

To move beyond simple spend thresholds, you can enhance your script by adding natural language processing (NLP) to classify the intent of wasted search terms.

1. Regex Negative Intent Tagging

Add regex patterns directly inside your Python processing pipeline to group wasted spend by category:

python

import re

INTENTPATTERNS = {

"Competitor": r"\b(competitor1|competitor2|login|portal)\b",

"Job Seeker": r"\b(salary|jobs|careers|hiring|internship|glassdoor)\b",

"Informational/DIY": r"\b(how to|diy|tutorial|guide|open source|free|pdf|template)\b",

"Support/Existing": r"\b(customer service|phone number|support|contact|refund)\b"

}

def classifyintent(searchterm: str) - str:

for category, pattern in INTENTPATTERNS.items():

if re.search(pattern, searchterm, re.IGNORECASE):

return category

return "Unclassified Intent"

Applying to dataframe

df['wastecategory'] = df['searchterm'].apply(classifyintent)

2. Calculating the True Cost of Unmanaged Intent

When running this categorization over a 30-day window, you will often find that specific intent categories (like "Support/Existing Users" or "Job Seekers") account for 10% to 18% of a campaign's total budget. Automatically tagging queries allows you to build universal negative keyword lists across your shared library, preventing future waste at scale.

---

Related Guides

• How to Use the Google Ads Search Terms Report to Cut Wasted Spend

• How to Find Negative Keywords in Google Ads (Step by Step)

• Google Ads Optimization Checklist: 15 Things to Check Every Week

---

Frequently Asked Questions

How often does the Google Ads API update search term data?

Google Ads search term metrics are typically processed with a 3 to 6-hour delay, though complete conversion attribution data can take up to 24 hours to finalize. Running your automated Python script once daily (such as at 6:00 AM for the previous day's data) provides an optimal balance between attribution accuracy and rapid waste detection.

What permissions are required to run search term queries via the API?

To query search term reports, your developer token needs at least Basic Access approval, and your OAuth credentials must have read access (https://www.googleapis.com/auth/adwords) to the target customer ID. If pulling data through an MCC, ensure your authenticated Google account has standard or administrative access to the manager account.

Why does my Python script show less total cost than the Google Ads UI campaign summary?

This discrepancy is caused by Google's search term privacy thresholds. Google only surfaces specific search term strings that have been queried by a sufficient number of users, grouping low-volume query costs into the campaign total without exposing the exact query text in the searchtermview API endpoint.