如何从Google Ads API中获取数据
(1) 我现在所在的地方,谷歌网站因为防火墙的原因无法访问。不过我在用Clash for Windows这个工具,能够顺利访问谷歌网站,浏览器上运行得很好。
(2) 我正在用Python在我的Windows 10笔记本电脑上的Jupyter Notebook里测试谷歌广告API,代码很简单,像下面这样:
import logging
logging.basicConfig(level=logging.INFO)
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
# Define the main function
def main(client, customer_id):
ga_service = client.get_service("GoogleAdsService")
query = """
SELECT
campaign.id,
campaign.name
FROM campaign
ORDER BY campaign.id
"""
# Issues a search request using streaming.
stream = ga_service.search_stream(customer_id=customer_id, query=query)
# Iterate through the results and print them
for batch in stream:
for row in batch.results:
print(
f"Campaign with ID {row.campaign.id} and name "
f"{row.campaign.name}"
)
# Load Google Ads client from storage
# Replace "PATH/TO/YOUR/google-ads.yaml" with the actual path to your file
googleads_client = GoogleAdsClient.load_from_storage(path=r"C:\Users\tomxi\google-ads.yaml", version="v15")
# Get customer ID from user input (optional)
# Replace with your desired method of obtaining the customer ID
customer_id = "xxxxxxxxxx"
# Call the main function
try:
main(googleads_client, customer_id)
except GoogleAdsException as ex:
print(
f'Request with ID "{ex.request_id}" failed with status '
f'"{ex.error.code().name}" and includes the following errors:'
)
for error in ex.failure.errors:
print(f'\tError with message "{error.message}".')
if error.location:
for field_path_element in error.location.field_path_elements:
print(f"\t\tOn field: {field_path_element.field_name}")
sys.exit(1)
(3) 但是我遇到了一个错误:
[TransportError: HTTPSConnectionPool(host='accounts.google.com', port=443): Max retries exceeded with url: /o/oauth2/token (Caused by SSLError(SSLEOFError(8, '\[SSL: UNEXPECTED_EOF_WHILE_READING\] EOF occurred in violation of protocol (_ssl.c:1006)')))][1]
(4) 我猜谷歌广告API可能使用了一些Clash for Windows无法处理的网络路径或其他东西。我不太确定该怎么检查和更改这些设置。请帮帮我。
1 个回答
0
你在Colab上运行脚本,但你引用的配置文件是在你本地电脑上的。
如果你想在Colab上使用这个文件,你需要先把你的Google Drive挂载上去,并把文件上传到那里。
不过,我强烈建议你不要把配置文件放在Colab上,因为里面包含了非常重要的秘密信息,比如你的Google Ads开发者密钥和你个人的Google账户刷新/访问令牌。