码迷,mamicode.com
首页 > Windows程序 > 详细

调用api接口获取IP地址的归属地

时间:2021-04-27 15:17:41      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:sts   文件   exce   时间   print   cep   filter   ons   请求头   

 

#
#一、填写请求头
#二、配置程序延迟时间
#三、填写源IP文件
#四、经了解,该接口限制一分钟采集45个
#

import requests
import json
import os
from fake_useragent import UserAgent
from xlwt import Workbook
import random
import time

def ip_filter(filename):
    fd = open(filename,r)
    for line in fd:
        ip = line.replace(\n,‘‘)
        ip_list.append(ip)
    fd.close()
    return ip_list

def api_select(ip_list):
    for num,ip_value in enumerate(ip_list):
        timeout = random.randint(0, 5)    #程序延迟时间,单位:秒
        print(等待时间:%s秒%(timeout))
        time.sleep(timeout)
        url_list1(ip_value,num)

def url_list1(ip_value,num):
    url1 = http://ip-api.com/json/%s % (ip_value)
    url2 = ?lang=zh-CN
    url = url1 + url2
    response_text(url,num)

def response_text(url,num):      #爬取json文本
    # headers = UserAgent().ie   #随机请求头
    try:
        print((-*10)+开始爬取+(-*10))
        response=requests.get(url,headers).text
        print((-*10)+爬取结束+(-*10))
        res = json.loads(response)
        api1(res)
    except Exception as e:
        time.sleep(10)    #发生异常,10秒后重连
        print(10秒后自动重连)
        response_text(url,num)   #重新调用

def api1(res):
    country = res.get(country)
    ipadd = res.get(query)
    ip_country[ipadd] = country
    excel_text(ip_country)

def excel_text(ip_country):    #程序写入excel
    w = Workbook()        # 创建一个工作簿
    ws = w.add_sheet(IP归属地统计)        # 创建一个工作表
    count = 0         # 计数
    i = 0   #控制行
    j = 0   #控制列
    for key, value in ip_country.items():
        ws.write(i, j, key)
        ws.write(i, j + 1, value)
        j = 0
        i += 1
        count += 1
    w.save(IP归属地统计.xls)
    print(统计的IP个数为:,count)

if __name__ == __main__:
    start = time.time()       #程序开始运行时间
    ip_country={}
    ip_list = []
    headers = {
        
    }
    #输入IP文件名(同一目录下,txt)
    filename = IP统计.txt       #填写源IP文件名
    ip_list = ip_filter(filename)
    api_select(ip_list)
    end = time.time()   #程序结束时间
    print(Running time: %s 分钟 % ((end - start)/60))  #统计运行时间

 

调用api接口获取IP地址的归属地

标签:sts   文件   exce   时间   print   cep   filter   ons   请求头   

原文地址:https://www.cnblogs.com/interpreter/p/14708256.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!