如何使用Python API在Google Ads中添加IP至黑名单?
使用Google Ads API添加IP地址至黑名单的修复方案
你提供的旧代码基于已弃用的v2版本Google Ads API,同时存在变量未定义、属性赋值方式过时等问题,以下是适配当前最新API版本(以v17为例)的完整修复方案:
旧代码的核心问题
- 依赖过时的API版本(v2),当前Google Ads API已更新至v17,旧版本接口大概率无法正常调用
campaign_service、customer_id、campaign_id等关键变量未初始化,直接引用会触发NameError- 属性赋值方式不符合新版本规范(比如多余的
.value调用)
修复后的完整代码
from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException def add_ip_blacklist(customer_id, campaign_id, ip_address): # 初始化Google Ads客户端 client = GoogleAdsClient.load_from_storage(path="google-ads.yaml") # 获取CampaignCriterion服务实例 campaign_criterion_service = client.get_service("CampaignCriterionService") # 创建CampaignCriterion操作对象 campaign_criterion_operation = client.get_type("CampaignCriterionOperation") campaign_criterion = campaign_criterion_operation.create # 标记为负向规则(即黑名单) campaign_criterion.negative = True # 关联目标广告系列 campaign_criterion.campaign = client.get_service("CampaignService").campaign_path( customer_id, campaign_id ) # 设置要屏蔽的IP地址 campaign_criterion.ip_block.ip_address = ip_address try: # 提交修改请求 response = campaign_criterion_service.mutate_campaign_criteria( customer_id=customer_id, operations=[campaign_criterion_operation] ) # 输出成功结果 for result in response.results: print(f"已添加IP黑名单规则:{result.resource_name}") except GoogleAdsException as ex: # 捕获并打印API错误详情 print("调用API时出错:") for error in ex.failure.errors: print(f"错误代码:{error.error_code}") print(f"错误信息:{error.message}") # 调用示例:替换为你的实际客户ID、广告系列ID和要屏蔽的IP add_ip_blacklist("123-456-7890", "123456789", "80.67.167.81")
关键注意事项
- 先确保安装最新版Google Ads Python库:
pip install --upgrade google-ads customer_id需带连字符(格式如"123-456-7890"),campaign_id可传入纯数字字符串或整数- 代码新增了异常捕获逻辑,方便排查权限不足、广告系列不存在等API调用错误
- 新版本API中,属性赋值无需再使用
.value,直接赋值即可(比如campaign_criterion.negative = True)
内容的提问来源于stack exchange,提问作者João Pedro Pimenta
相关产品推荐
相关产品推荐

