请求IP与返回结果IP不一致的技术问题咨询
问题原因
你遇到的问题是因为file.readline()读取IP时,会包含行末的换行符\n。当你把这个带换行的IP拼接到API URL后,实际请求的地址是https://geolocation-db.com/jsonp/216.128.74.178\n——这个无效的URL会让Geolocation-DB API无法识别你传入的IP,于是默认返回你设备当前的网络出口IP(也就是172.58.146.151)。
从你的输出也能验证这一点:216.128.74.178和****不在同一行,说明ip_add里包含换行符,导致打印时自动换行。
修复方案
只需要在读取IP后,用strip()方法去掉首尾的空白字符(包括换行符、空格)即可:
import os import sys import re import time import requests import json file_name = input("Enter IP list filename: ") with open(file_name, 'r') as file: ip_add = file.readline().strip() # 添加strip()去除换行符等空白 print(ip_add,"****") request_url = 'https://geolocation-db.com/jsonp/' + ip_add # 可选:打印URL确认格式是否正确 # print(request_url) response = requests.get(request_url) print(response) result = response.content.decode() result = result.split("(")[1].strip(")") result = json.loads(result) print(result)
额外优化建议
- 如果你的IP列表有多行,可以用循环批量处理:
with open(file_name, 'r') as file: for line in file: ip_add = line.strip() if not ip_add: # 跳过空行 continue # 重复后续的API请求逻辑 request_url = 'https://geolocation-db.com/jsonp/' + ip_add response = requests.get(request_url) # ... 解析响应的代码 time.sleep(1) # 添加延迟,避免频繁请求触发API限制
内容的提问来源于stack exchange,提问作者John Hunter
相关产品推荐
相关产品推荐

