Python调用Truecaller API获取手机号名称遇连接错误求助
问题
我编写了一个用于获取手机号对应名称的Python脚本,但运行时出现连接错误。
脚本代码
import pandas as pd import requests # Your API key from Truecaller api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # Path to the Excel file excel_file_path = 'Ash.xlsx' # Country Code #country_code = 'GH' # Read the Excel file df = pd.read_excel(excel_file_path) # Assuming the phone numbers are in a column named 'PhoneNumber' phone_numbers = df['PhoneNumber'] # URL for Truecaller API url = 'https://api.truecaller.com/v1/search/+233' # Create a new column for the names df['Name'] = None for index, number in phone_numbers.items(): response = requests.get(url + str(number), headers={'Authorization': 'Bearer ' + api_key}) if response.status_code == 200: data = response.json() df.at[index, 'Name'] = data.get('name', 'Not Found') else: df.at[index, 'Name'] = 'Failed to Fetch' # Save the updated DataFrame back to Excel df.to_excel('updated_' + excel_file_path, index=False) print("Finished updating the Excel file.")
错误信息
File "/Users/user/Desktop/Py/.venv/lib/python3.9/site-packages/requests/adapters.py", line 700, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.truecaller.com', port=443): Max retries exceeded with url: /v1/search/+233540121351 (Caused by NameResolutionError("<urllib3.connection.HTTPSConnection object at 0x117708f70>: Failed to resolve 'api.truecaller.com' ([Errno 8] nodename nor servname provided, or not known)"))
解决方案
排查DNS解析与网络连接
错误核心是无法解析api.truecaller.com域名,先在终端执行以下命令验证:ping api.truecaller.com # 或者 nslookup api.truecaller.com如果无法解析,尝试:
- 切换网络环境(如WiFi换手机热点)
- 手动配置公共DNS(如8.8.8.8或1.1.1.1)
验证Truecaller API的有效性
- 确认API端点是否正确,核对官方文档确认当前可用的API路径
- 检查API密钥是否有效、未过期,可通过Postman等工具直接调用API测试响应
代码优化与容错
- 添加重试机制,避免单次网络波动导致失败:
from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry # 初始化带重试的会话 session = requests.Session() retry_strategy = Retry( connect=3, backoff_factor=0.5, status_forcelist=[429, 500, 502, 503, 504] ) adapter = HTTPAdapter(max_retries=retry_strategy) session.mount('https://', adapter) # 遍历号码查询 for index, number in phone_numbers.items(): full_url = f'https://api.truecaller.com/v1/search/+233{str(number)}' try: response = session.get(full_url, headers={'Authorization': 'Bearer ' + api_key}) response.raise_for_status() # 主动抛出HTTP错误 data = response.json() df.at[index, 'Name'] = data.get('name', 'Not Found') except requests.exceptions.RequestException as e: df.at[index, 'Name'] = f'Failed: {str(e)[:50]}' # 截断过长错误信息 - 避免直接拼接URL,确保号码格式正确(如无多余空格、特殊字符)
- 添加重试机制,避免单次网络波动导致失败:
内容的提问来源于stack exchange,提问作者RICHARD McTETTEH
相关产品推荐
相关产品推荐

