绕过防火墙限制,从 Google 广告 API 检索数据:分步指南
2024-03-24 14:05:09
绕过防火墙限制:从 Google 广告 API 检索数据
问题陈述
使用 Python 在 Jupyter Notebook 中测试 Google 广告 API 时,由于防火墙限制而无法访问 Google 网站。使用 Clash for Windows 绕过防火墙后,通过 Jupyter Notebook 访问 Google 广告 API 时仍会遇到错误。
解决方案
步骤 1:检查网络连接
确保 Clash for Windows 设置正确,并且可以成功访问 Google 网站。在浏览器中打开 Google 网站进行测试。
步骤 2:检查端口
检查 Clash for Windows 设置,确保允许 HTTPS 连接的 443 端口。
步骤 3:禁用或调整 Clash for Windows 代理
尝试暂时禁用 Clash for Windows 代理或调整代理设置。
步骤 4:使用 VPN
如果上述方法无效,可以使用 VPN 绕过防火墙限制。选择信誉良好的 VPN 服务,并确保它允许访问 Google 广告 API 所需的端口。
步骤 5:联系 Google 支持
如果所有方法都失败,请联系 Google 支持。他们可以提供进一步的帮助,并排除 API 相关的问题。
代码示例
以下是修改后的代码,可以在绕过防火墙后使用:
import logging
logging.basicConfig(level=logging.INFO)
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
# Replace with your desired method of obtaining the customer ID
customer_id = "xxxxxxxxxx"
# 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")
# 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)
结论
通过遵循本文提供的步骤,你可以绕过防火墙限制,并使用 Jupyter Notebook 访问 Google 广告 API。通过调整代理设置、使用 VPN 或联系 Google 支持,你可以解决与网络连接相关的错误,并成功检索数据。
常见问题解答
1. 如何绕过防火墙限制?
使用 Clash for Windows、VPN 或调整代理设置。
2. Google 广告 API 使用哪些端口?
443 端口。
3. 如果所有方法都失败,我该怎么办?
联系 Google 支持。
4. 我可以使用其他编程语言吗?
是的,Google 广告 API 支持多种语言,包括 Java、Python、C# 和 PHP。
5. 我如何获得 Google 广告 API 的访问权限?
创建 Google Ads 帐号,并遵循 Google 开发人员文档中的说明。