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

 

##一、填写请求头#二、配置程序延迟时间#三、填写源IP文件#四、经了解,该接口限制一分钟采集45个#import requestsimport jsonimport osfrom fake_useragent import UserAgentfrom xlwt import Workbookimport randomimport timedef ip_filter(filename): fd = open(filename,r) for line in fd: ip = line.replace(\n,‘‘) ip_list.append(ip) fd.close() return ip_listdef 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)) #统计运行时间

 

相关文章