You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Requests调用SimilarWeb API遇getaddrinfo failed错误求助

问题

首次尝试通过SimilarWeb API获取数据,使用Python Requests编写了如下代码:

api_key = '3dac084d01e55d6e9a18c0d33eiu6341'
url = 'https://api.similarweb.com/v1/website/bbc.com/total-traffic-and-engagement/average-visit-duration?api_key={{similarweb_api_key}}&start_date=2017-11&end_date=2018-01&country=gb&granularity=monthly&main_domain_only=false&format=json'
headers = {'Ocp-Apim-Subscription-Key': '{key}'.format(key=api_key)}

Visits = requests.get(url, headers=headers).json()

执行后出现如下网络错误:

ConnectionError: HTTPSConnectionPool(host='api.similarweb.com', port=443): Max retries exceeded with url: /v1/website/bbc.com/total-traffic-and-engagement/average-visit-duration?api_key=%7B%7Bsimilarweb_api_key%7D%7D&start_date=2017-11&end_date=2018-01&country=gb&granularity=monthly&main_domain_only=false&format=json (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x000001A3B68476A0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

开发环境为Spyder,求解决办法。

解决办法
  • 修正API Key占位符:URL中保留了模板占位符{{similarweb_api_key}},未替换为实际的api_key变量。可用f-string替换:
    url = f'https://api.similarweb.com/v1/website/bbc.com/total-traffic-and-engagement/average-visit-duration?api_key={api_key}&start_date=2017-11&end_date=2018-01&country=gb&granularity=monthly&main_domain_only=false&format=json'
    
  • 排查网络连通性:getaddrinfo failed表示无法解析目标域名,先确认Spyder所在环境能正常访问外网,可尝试在浏览器打开api.similarweb.com测试连通性。
  • 确认API认证方式:SimilarWeb API部分接口仅需URL传参或仅需Header传参,无需同时使用两种方式。可去掉其中一种认证参数后重试。
  • 验证API Key有效性:检查api_key是否正确、未过期,且具备访问该接口的权限。

内容的提问来源于stack exchange,提问作者Seedizens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:10:56