Python3调用接口查询IP信息

看到网上有那么多的开放接口,于是就想尝试一下接口程序,于是就找了网上公开的IP接口,试了几个还是淘宝的比较稳定。也比较好用,下面做简单的介绍。

开发环境:windows pycharm
调用相关的模块
123 import json  #解析返回jason格式的结果
import requests #调用访问web
import urllib.parse #拼接url

淘宝IP地址库:http://ip.taobao.com/index.php

API相关资料:

1. 请求接口(GET):
/service/getIpInfo.php?ip=[ip地址字串]
2. 响应信息:
(json格式的)国家 、省(自治区或直辖市)、市(县)、运营商
3. 返回数据格式:
{"code":0,"data":{"ip":"210.75.225.254","country":"\u4e2d\u56fd","area":"\u534e\u5317",
"region":"\u5317\u4eac\u5e02","city":"\u5317\u4eac\u5e02","county":"","isp":"\u7535\u4fe1",
"country_id":"86","area_id":"100000","region_id":"110000","city_id":"110000",
"county_id":"-1","isp_id":"100017"}}
其中code的值的含义为,0:成功,1:失败。

从上面的api的格式我们可以看到他包含很多的字段,在我们api开发对接工程中只需要按照自己的需求格式化输出就好。

过程分析:
1、首先是找相关的接口以及接口的相关参数
2、用urllib.parse拼接完整的URL并提交
3、接收返回值
4、将返回值转换成jash格式,并按自己的需求格式化输出
 
#!/bin/env/python
import json
import requests
import urllib.parse
dataip=  input("please  input your ipaddress:") #输入IP
url=" #地址 
data={}  #定义一个空字典
data["ip"]=dataip  #字典中的IP
data = urllib.parse.urlencode(data).encode("utf-8")#拼接rul
 
response = urllib.request.urlopen(url, data) #post提交数据
html = response.read().decode("utf-8")  #接收返回数据
#print(html)
tag=json.loads(html,encoding='utf8') #josh格式转换
#print(tag)
ip=tag["data"]["ip"]  #要查询IP
city=tag["data"]["city"]#城市
area=tag["data"]["area"]#区域
isp=tag["data"]["isp"] #ISP
county=tag["data"]["county"]#市区
country=tag["data"]["country"]#国家
print("您输入的IP:%s\n所在城市区域:%s%s%s\n运营商:%s%s"%(ip,country,city,
 
运行程序
please  input your ipaddress:114.98.241.95
返回结果:
您输入的IP:114.98.241.95
所在城市区域:中国合肥市
运营商:中国电信

猜你喜欢

转载自www.linuxidc.com/Linux/2017-04/142763.htm
今日推荐