一,事先新建數據庫,django,表 origin ,將ip事先導入進去
CREATE TABLE `origin` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `ip` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `country` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `region` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `city` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `isp` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2612 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
二,運行python
#!/usr/local/bin/python #coding: utf-8 import json,pymysql,time from urllib import request def get_conn(): conn = pymysql.connect(host='192.168.80.200', port=3306, user='root', passwd='123', db='django', charset='utf8') return conn def query_all(cur, sql, args): cur.execute(sql, args) return cur.fetchall() def ip_region(): conn = get_conn() cur = conn.cursor() k=j=0 # k記錄獲得502網關錯誤,j記錄輪尋次數 sql_ip = 'select ip from origin where country is NULL;' while query_all(cur=cur,sql=sql_ip,args=None): results=query_all(cur=cur,sql=sql_ip,args=None) for i in results: res = url(i[0]) #獲取指定ip的歸屬地函數 if res: sql_add = "update origin set country='"+res[0]+"',region='"+res[1]+"',city='"+res[2]+"',isp='"+res[3]+"' where ip='"+i[0]+"';" # print(sql_add) cur.execute(sql_add) conn.commit() else: k=k+1 print('====>get 502:',k) time.sleep(0.5) j=j+1 print('========>second round:',j) cur.close() conn.close() return k,j def url(ip): url = "http://ip.taobao.com/service/getIpInfo.php?ip="+ ip #淘寶查ip歸屬地請求api try: jsondata = json.loads(request.urlopen(url).read()) if jsondata['code'] == 1: jsondata['data'] = {'region': '', 'city': '', 'isp': ''} print(jsondata['data']['country'], jsondata['data']['region'], jsondata['data']['city'], jsondata['data']['isp']) return ( jsondata['data']['country'], jsondata['data']['region'], jsondata['data']['city'], jsondata['data']['isp']) except: return False if __name__ == "__main__": start_time = time.asctime(time.localtime()) result = ip_region() print('get 502 counts:',result[0]) print('round counts:',result[1]) print('start time:',start_time) print('end time:',time.asctime(time.localtime()))