jsoup爬取ip查询网址获取登录ip地理位置

jsoup爬取ip查询网址获取登录ip地理位置


####: 代码
我使用的是 https://ip.cn/ip/112.45.165.150.html 这个网址爬取,第一次用jsoup,大佬勿喷,嘻嘻

package com.vicovico.util;
import com.vicovico.common.DefaultEnum;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
 * @Author : WuXiang
 * @Description : jsoup爬取ip查询网址获取登录ip地理位置
 * @Date : create by WuXiang in 2021-9-20
 * @Email : 1796207106@qq.com
 * @Since : JDK 1.8
 * @PackageName : com.vicovico.util;
 * @Version : 1.0.0
 */
public class LocationUtil {
    /**
    本机ip
     */
    private static List<String> localIPS = Arrays.asList("0:0:0:0:0:0:0:1","127.0.0.1");
    /**
     * 根据ip获取地区
     * @param ip
     * @return
     */
    public static String getLoginArea(String ip)  {
        String loginArea = "未知";
        if(DefaultEnum.getLocalIPS().contains(ip)){
            return "本机访问";
        }
        try{
        Document document = Jsoup.connect("https://www.ip.cn/ip/" + ip + ".html").get();
            // 通过元素id值来获取对应的节点
            Element element = document.getElementById("tab0_address");
            int lastEmptyIndex = StringUtils.lastIndexOf(element.text()," ");
            loginArea = StringUtils.substring(element.text(),0,lastEmptyIndex);
    } catch (IOException e) {
            e.printStackTrace();
        }finally {
            return loginArea;
        }
    }
}

结果如下:

jsoup爬取ip查询网址获取登录ip地理位置

上一篇:org.jsoup.UnsupportedMimeTypeException


下一篇:Java Jsoup 解析处理百度谷歌搜索结果的示例代码