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

基于RESTful API批量验证列表中电话号码的技术实现求助

代码问题排查与修正

以下是你的代码中存在的问题及对应的修复方案:

1. 未定义的颜色变量

代码中使用了cy、res、gr、yl、red这些终端颜色控制变量,但未提前定义。如果需要颜色输出,需先声明这些变量:

cy = '\033[96m'
res = '\033[0m'
gr = '\033[92m'
yl = '\033[93m'
red = '\033[91m'

不需要颜色的话,直接删除这些变量即可。

2. 字典参数语法错误

params字典中'number' = 'phone_number' + str(i)写法错误:

  • 字典键值对必须用冒号:分隔,而非等号=
  • 拼接逻辑冗余:i已是列表中的号码字符串,无需和phone_number变量名拼接,直接用i即可

修正后:

params = {
    'user-id': 'my user id goes here',
    'api-key': 'my api key goes here',
    'number': i
}

3. 变量名不匹配

API返回结果被解析到result变量,但后续判断和输出都用了未定义的answer变量,所有answer需替换为result。

4. 条件判断逻辑错误

if answer["valid==true"]是错误写法,API返回的valid字段是布尔值(True/False),正确判断方式:

if result["valid"]:

5. 文件操作未正确释放资源

直接用open()打开文件后未调用close(),易导致资源泄漏。推荐用with语句自动管理文件:

# 替换有效号码写入逻辑
with open(f'Result/valid.txt', 'a+', encoding='utf-8') as save:
    save.write(f"{i}\n")

# 替换无效号码写入逻辑
with open('Result/invalid.txt', 'a+', encoding='utf-8') as dk:
    dk.write(f"{i}\n")

6. 目录不存在的风险

如果Result目录不存在,写入文件会抛出FileNotFoundError,需提前创建目录:

import os
os.makedirs('Result', exist_ok=True)  # 已存在则不报错

7. 缺少异常处理

请求API时可能遇到网络错误、权限问题等,需添加异常捕获避免程序崩溃:

try:
    response = request.urlopen(req)
    result = json.loads(response.read().decode("utf-8"))
    # 后续判断逻辑
except Exception as e:
    print(f"{red}{i} 请求失败: {str(e)}{res}")
    with open('Result/failed.txt', 'a+', encoding='utf-8') as f:
        f.write(f"{i}\n")
    continue

修正后的完整代码

from urllib import request, parse
import json
import os

# 定义终端颜色变量(可选,不需要可删除)
cy = '\033[96m'
res = '\033[0m'
gr = '\033[92m'
yl = '\033[93m'
red = '\033[91m'

# 创建Result目录
os.makedirs('Result', exist_ok=True)

# 读取号码列表
phone_number = open(input(f'\n{cy}Enter Phone Number List{res} : '),'r').read().splitlines()

print('------------------------------------------------------------------')

for i in phone_number :
    url = 'https://neutrinoapi.net/phone-validate'
    params = {
        'user-id': 'my user id goes here',
        'api-key': 'my api key goes here',
        'number': i
    }

    postdata = parse.urlencode(params).encode()
    req = request.Request(url, data=postdata)
    
    try:
        response = request.urlopen(req)
        result = json.loads(response.read().decode("utf-8"))

        if result["valid"]:
            print(f'{gr}{result["number"]}{res}{yl} => {cy}{result["valid"]}{res}')
            with open(f'Result/valid.txt', 'a+', encoding='utf-8') as save:
                save.write(f"{i}\n")
        else:
            print(f'{red}{result["number"]} => Die{res}')
            with open('Result/invalid.txt', 'a+', encoding='utf-8') as dk:
                dk.write(f"{i}\n")
    except Exception as e:
        print(f"{red}{i} 请求失败: {str(e)}{res}")
        with open('Result/failed.txt', 'a+', encoding='utf-8') as f:
            f.write(f"{i}\n")
        continue

input('Click Enter For Exit ...!')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:27:34