Python代理/IP信息检查器脚本故障:无法进入try执行块
代理检查脚本修复方案
问题根源及修复点
代理地址未正确格式化
原代码中代理字符串写法'socks5h://{proxyl}'只是普通字符串,没有将变量proxyl替换为实际代理地址,导致请求无法使用代理,直接触发异常进入except块。需要用f-string完成变量插入:f'socks5h://{proxyl}'。函数依赖全局变量
get_location()直接使用外部循环的line变量,耦合性高且容易出错。改为将代理字符串作为参数传入函数,逻辑更清晰。异常捕获过于宽泛
原代码用except:捕获所有异常,无法定位具体错误(比如代理连接超时、格式错误等)。改为捕获requests相关的具体异常,并打印错误信息,方便调试。冗余代码清理
循环中lines = lines + line属于无用代码,直接删除即可。输出格式优化
原代码直接把字典转成字符串写入文件,可读性差。改用json.dumps()将结果转为标准JSON格式写入,方便后续读取解析。
修改后的完整代码
import requests import json from requests.exceptions import RequestException from fake_useragent import UserAgent ua = UserAgent() def get_location(proxy_str): proxyl = proxy_str.strip() # 处理代理格式错误的情况 try: pip, port = proxyl.split(':') except ValueError: print(f"代理格式错误:{proxyl},跳过该代理") return None try: # 正确格式化代理地址 proxies = { 'http': f'socks5h://{proxyl}', 'https': f'socks5h://{proxyl}' } # 使用代理请求httpbin获取真实出口IP iresponse = requests.get( 'http://httpbin.org/ip', headers={'User-Agent': str(ua.random)}, timeout=10, proxies=proxies ).json() ip = iresponse["origin"] checker = ip # 获取IP地理位置信息 response = requests.get( f'https://ipapi.co/{ip}/json/', headers={'User-Agent': str(ua.random)} ).json() print(f"代理 {proxyl} 可用,出口IP:{checker}") except RequestException as e: # 打印具体错误信息,方便排查 print(f"代理 {proxyl} 请求失败:{str(e)}") # 无代理情况下获取本地IP(可选逻辑,可根据需求调整) iresponse = requests.get( 'http://httpbin.org/ip', headers={'User-Agent': str(ua.random)}, timeout=10 ).json() checker = iresponse["origin"] # 尝试查询代理IP的信息(如果代理IP本身可查) response = requests.get( f'https://ipapi.co/{pip}/json/', headers={'User-Agent': str(ua.random)} ).json() print(f"本地出口IP:{checker}") location_data = { "ip": pip, "proxy": proxyl, "city": response.get("city"), "region": response.get("region"), "country": response.get("country_name"), "postal": response.get("postal"), "timezone": response.get("timezone"), "org": response.get("org"), "checker": checker } return location_data with open('det.txt', 'w', encoding='utf-8') as z: with open('proxy.txt', "r", encoding='utf-8') as p: for line in p.readlines(): # 跳过空行 if not line.strip(): continue print(f"正在测试代理:{line.strip()}") result = get_location(line) if result: # 写入JSON格式数据,每行一个对象 z.write(json.dumps(result, ensure_ascii=False) + '\n')
额外说明
- 如果你的代理不是
socks5h类型(比如是http/https代理),需要把proxies里的socks5h://改成http://或https://。 - 代码中新增了代理格式错误的处理,避免因
proxy.txt中存在格式错误的代理导致脚本崩溃。 - 写入文件时指定了
encoding='utf-8',避免中文乱码问题。
内容的提问来源于stack exchange,提问作者Lesleyana Belenu
相关产品推荐
相关产品推荐

