高精确IP查询接口Python语言附源代码

bccd009fd02439b7b6c7c7bcc16844d3

查询IP

最近有这么个需求需要查询本机的IP地址精确查询,县级市,抓取了站长工具和ip138这个两个网站的接口.非常准确.站长工具还支持IPV6的地址查询

地址为空则是默认查询本机的IP地址!由于是抓取的网络的接口可能随着网站更新不能用的情况,如果不能用了可以留言给小编看到了后会第一时间更新代码的.

.

import os,time,hashlib,win32api,requests,re
from  lxml import etree

class ipcx:
    'IP查询集合接口'
    def __init__(self,IP):
        self.IP=IP
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'}
        self.proxies = {'http': 'http://127.0.0.1:10809', 'https': 'http://127.0.0.1:10809'}

    def zzip(self):
      '站长工具地址,支持ipv4,ipv6 判断'
      url='https://ip.tool.chinaz.com/'+self.IP
      r=requests.get(url=url,headers=self.headers,proxies=self.proxies,timeout=7)
      r.encoding = r.apparent_encoding
      r = etree.HTML(r.text)
      if self.IP=='':
          city=r.xpath('//*[@id="rightinfo"]/div[1]/dl/dd[2]/text()')[0]
          ip=r.xpath('//*[@id="rightinfo"]/div[1]/dl/dd[1]/text()')[0]
          city=city.replace(' ','').replace('中国','')
          print(ip+'|'+city)
      else:
          try:
              city = r.xpath('//*[@id="leftinfo"]/div[3]/div[2]/div[2]/span[4]/em/text()')[0] #ipv4查询
              city = city.replace(' ', '').replace('中国', '')
              print(self.IP + '|' + city)
          except:
              city = r.xpath('//*[@id="leftinfo"]/div[3]/div[2]/p[2]/span[2]/text()')[0]  #ipv6查询
              city = city.replace(' ', '').replace('中国', '')
              print(self.IP + '|' + city)

    def ip138(self):
        'ip138接口地址只支持本地查询ipv4'
        url='https://2022.ip138.com/'
        r=requests.get(url=url,headers=self.headers,proxies=self.proxies,timeout=7)
        r.encoding=r.apparent_encoding
        r=etree.HTML(r.text)
        city=r.xpath('/html/body/p[1]/text()[2]')[0]
        city=city.replace(' ','').replace(']来自:中国','')
        ip=r.xpath('/html/body/p[1]/a/text()')[0]
        print(ip+'|'+city)



if __name__ == '__main__':
  ip=ipcx('ip')#输入ip地址 支持ipv4,ipv6
  ip.zzip()

 

THE END