我有一个包含IP的DataFrame common_ips,如下所示。

我需要完成两项基本任务:
以下是我正在做的事情:
import json
import urllib
import re
baseurl = 'http://ipinfo.io/' # no HTTPS supported (at least: not without a plan)
def isIPpublic(ipaddress):
return not isIPprivate(ipaddress)
def isIPprivate(ipaddress):
if ipaddress.startswith("::ffff:"):
ipaddress=ipaddress.replace("::ffff:", "")
# IPv4 Regexp from https://stackoverflow.com/questions/30674845/
if re.search(r"^(?:10|127|172\.(?:1[6-9]|2[0-9]|3[01])|192\.168)\..*", ipaddress):
# Yes, so match, so a local or RFC1918 IPv4 address
return True
if ipaddress == "::1":
# Yes, IPv6 localhost
return True
return False
def getipInfo(ipaddress):
url = '%s%s/json' % (baseurl, ipaddress)
try:
urlresult = urllib.request.urlopen(url)
jsonresult = urlresult.read() # get the JSON
parsedjson = json.loads(jsonresult) # put parsed JSON into dictionary
return parsedjson
except:
return None
def checkIP(ipaddress):
if (isIPpublic(ipaddress)):
if bool(getipInfo(ipaddress)):
if 'bogon' in getipInfo(ipaddress).keys():
return 'Private IP'
elif bool(getipInfo(ipaddress).get('org')):
return getipInfo(ipaddress)['org']
else:
return 'No organization data'
else:
return 'No data available'
else:
return 'Private IP'并将其应用于我的common_ips DataFrame
common_ips['Info'] = common_ips.IP.apply(checkIP)但花的时间比我预期的要长,。对于一些IP来说,它是提供的不正确的信息。
例如:

当我交叉检查时,它应该是AS19902 Department of Administrative Services

和

我在这里错过了什么?我怎样才能以一种更毕加索的方式完成这些任务呢?
发布于 2019-02-11 08:31:36
毛毯except:基本上总是一个bug。您正在返回None,而不是处理来自服务器的任何异常或错误响应,当然,您的其余代码无法恢复。
作为调试的第一步,只需取出try/except处理即可。也许这样,您就可以找到一种方法,为您知道如何从其中恢复的某些情况下,返回一个更详细的错误处理程序。
def getipInfo(ipaddress):
url = '%s%s/json' % (baseurl, ipaddress)
urlresult = urllib.request.urlopen(url)
jsonresult = urlresult.read() # get the JSON
parsedjson = json.loads(jsonresult) # put parsed JSON into dictionary
return parsedjson也许checkIP中的调用代码应该有一个try/except,例如,如果服务器表示您运行得太快,那么在休眠一段时间后再试一次。
(在没有授权令牌的情况下,看起来您使用的是该服务的免费版本,无论如何,它可能没有任何保证。也可以考虑使用他们推荐的库--我还没有更详细地研究过它,但是我可以想象它至少知道在服务器端错误的情况下如何运行。几乎可以肯定的是,它也更像毕达通,至少在某种意义上,你不应该重新发明已经存在的东西。)
https://stackoverflow.com/questions/54626047
复制相似问题