python 实现筛选IP归属

import json
import requests
import time
import random

url = 'https://ip.useragentinfo.com/json?ip='
headers = {
   # 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
    'User-Agent': 'User-Agent:Mozilla/5.0'
    }
province_list=["香港特别行政区","台湾省",]
with open("./CN_IP.txt") as f:
    for line in f.readlines():
        ip = line.strip() # 把末尾的'\n'删掉
        get_url = url + ip
        print(get_url)
        res = requests.get(get_url,headers=headers)

        # print(res.status_code)
        print(res.json())
        # break
        try:
            if res.json()["country"] == "中国":
                if res.json()['province']  in province_list:
                    with open("./CN_IP_xg_tw.txt","a+") as cn_file:
                        cn_file.write(ip+'\n')

                    print("add CN {}".format(ip))
                else:
                    with open("./nelu.txt","a+") as other_file:
                        other_file.write(ip+'\n')
                    print(ip)
                # time.sleep(random.randint(0,1))
        except Exception as ex:
            print("--err--")
            with open("./error_IP.txt", "a+") as other_file:
                other_file.write(ip + '\n')
            print(ip)









版权声明:本文为IO_print原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。