python实现查询IP地址所在地

yipeiwu_com7年前Python基础

使方法一、用IP138数据库查询域名或IP地址对应的地理位置。

#-*- coding:gbk -*-
import urllib2
import re
 
try:
 while True:
  ipaddr = raw_input("Enter IP Or Domain Name:")
  if ipaddr == "" or ipaddr == 'exit':
   break
  else:
   url = "http://www.ip138.com/ips138.asp?ip=%s&action=2" % ipaddr
   u = urllib2.urlopen(url)
   s = u.read()
   #Get IP Address
   ip = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',s)
   print "\n****** Below Result From IP138 Database *****"
   print "IP Address:",ip[0]
   #Get IP Address Location
   result = re.findall(r'(<li>.*?</li>)',s)
   for i in result:
    print i[4:-5]
   print "*"*45
   print "\n"
 
except:
 print "Not Data Find"

方法二、本来想调用阿里的ip接口查询ip归属地。结果发现阿里的接口非常不给力,主要是不准确,不过是免费的且有地区和ISP的信息。以下是实现代码

# -*- coding: utf-8 -*-
import requests
 
def checkip(ip):
 
  URL = 'http://ip.taobao.com/service/getIpInfo.php'
  try:
    r = requests.get(URL, params=ip, timeout=3)
  except requests.RequestException as e:
    print(e)
  else:
    json_data = r.json()
    if json_data[u'code'] == 0:
      print '所在国家: ' + json_data[u'data'][u'country'].encode('utf-8')
      print '所在地区: ' + json_data[u'data'][u'area'].encode('utf-8')
      print '所在省份: ' + json_data[u'data'][u'region'].encode('utf-8')
      print '所在城市: ' + json_data[u'data'][u'city'].encode('utf-8')
      print '所属运营商:' + json_data[u'data'][u'isp'].encode('utf-8')
    else:
      print '查询失败,请稍后再试!'
 
ip={'ip': '202.102.193.68'}
checkip(ip)

但是多次查询发现ip归属地不准确,于是使用17mon的ip查询接口。但是17mon分付费和免费的库接口,我用的免费的测试,接口返回的字段有限,只有国家、省份、城市。代码如下

# -*- coding: utf-8 -*-
import requests
 
def lookup(ip):
 
  URL = 'http://freeipapi.17mon.cn/' + ip
  try:
    r = requests.get(URL, timeout=3)
  except requests.RequestException as e:
    print(e)
 
  json_data = r.json()
  print '所在国家:' + json_data[0].encode('utf-8')
  print '所在省份:' + json_data[1].encode('utf-8')
  print '所在城市:' + json_data[2].encode('utf-8')
  return(ip)
 
ip='202.104.15.102'
lookup(ip)

测试也不错,公司要使用还是选择购买付费的库查询接口吧。
本文部分出自 “老徐的私房菜” 博客,转载请与作者联系!

以上所述就是本文的全部内容了希望大家能够喜欢。

相关文章

详解用python实现基本的学生管理系统(文件存储版)(python3)

这个是升级的版本,比较进阶一点的,相对与之前的文件管理系统,数据只是存储到了内存中,而不是存储到硬盘上,我们想让文件存储到硬盘上的话,一个是存储到文件里,一个是存储到数据库中,存储到数据...

解决python中用matplotlib画多幅图时出现图形部分重叠的问题

1.解决方法:使用函数 tight_layout() 2.具体使用方法 import matplotlib.pyplot as plt fig = plt.figure()...

Python常用的json标准库

当请求 headers 中,添加一个name为 Accept,值为 application/json 的 header(也即“我”(浏览器)接收的是 json 格式的数据),这样,向服务...

PyQt5每天必学之创建窗口居中效果

PyQt5每天必学之创建窗口居中效果

本文实例为大家分享了PyQt5如何能够创建在桌面屏幕上居中窗口的具体代码,供大家参考,具体内容如下 下面的脚本说明我们如何能够创建在桌面屏幕上居中的窗口。 #!/usr/bin/py...

Python将文本去空格并保存到txt文件中的实例

如下所示: #encoding=utf-8# x=raw_input("Please enter a text: ") y=x.replace(" ","") f = open(...