无法理解为什么我会得到这个输出:
输入 IP 列表文件名:nearmeips.txt 216.128.74.178 ****
{'country_code': 'US', 'country_name': 'United States', 'city': 'Antioch', 'postal': '37013' ,“纬度”:36.0595,“经度”:-86.6592,“IPv4”:“172.58.146.151”,“州”:“田纳西州”}
当 216.128.74.178 是我的近迈普列表的顶部时。
我从未将172.58.146.178 传递到该站点。这是代码。
import os
import files
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()
print(ip_add,"****")
request_url = 'https://geolocation-db.com/jsonp/' + ip_add
response = requests.get(request_url)
print(response)
result = response.content.decode()
# Clean the returned string so it just contains the dictionary data for the IP address
result = result.split("(")[1].strip(")")
# Convert this data into a dictionary
result = json.loads(result)
print(result)
我唯一能想到的就是在非root手机中使用termux,但我是编码新手,所以我很困惑。
您的问题是
readline
方法返回带有尾随换行符的行:
>>> fd = open('nameips.txt')
>>> ip = fd.readline()
>>> ip
'216.128.74.178\n'
这会导致无效的 IP 地址,因此远程 API 会做出响应,就好像您没有传递任何地址一样(并返回有关 your 地址的信息)。您需要删除该换行符。一种选择是对
strip()
返回的值调用 readline
:
with open(file_name, 'r') as file:
ip_add = file.readline().strip()
通过此更改,您的代码将按预期工作:
Enter IP list filename: nameips.txt
216.128.74.178 ****
<Response [200]>
{'country_code': 'US', 'country_name': 'United States', 'city': None, 'postal': None, 'latitude': 37.751, 'longitude': -97.822, 'IPv4': '216.128.74.178', 'state': None}