python經過淘寶接口獲取ip歸屬地

說明藍色=命令名稱php

淺綠=命令參數html

淺藍=選項python

紫色=目錄json

系統環境:windows 7 32位windows

python版本:Python 2.7.3app

代碼以下:socket

  
  
  
  
    • #!/usr/bin/env python
    • #-*- coding:utf-8 -*-
    • #Author:left_left
  1. import socket  
  2. import json  
  3. def json_info(data):  
  4.     data = json.loads(data)  
  5.     if data["code"]:  
  6.         return False 
  7.     else:  
  8.         return data["data"]  
  9.    
  10. def get_addr(ip):  
  11.     head_info = "GET /service/getIpInfo.php?ip=%s HTTP/1.1\r\n" % ip  +\  
  12.         "Host:ip.taobao.com\r\n" +\  
  13.     "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:20.0) Gecko/20100101 Firefox/20.0\r\n" +\  
  14.     "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n\r\n" 
  15.     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  16.     addr = socket.gethostbyname("ip.taobao.com")  
  17.     s.connect((addr, 80))  
  18.     s.send(head_info)  
  19.     info = s.recv(4096)  
  20.     json_data = info.split("\r\n")  
  21.     return json_info(json_data[-4])  
  22.     s.close()  
  23.  
  24. def ip_read():  
  25.     ip_f = open("./ip")  
  26.       
  27.     for line in ip_f:  
  28.         ip = line.split("/")  
  29.           
  30.         if len(ip)>1:  
  31.             info = get_addr(ip[0])  
  32.             if info:  
  33.                 data = " ".join([line.strip("\n"), info["ip"], info["country"],  
  34.                             info["city"],info["region"], info["area"], info["isp"]])  
  35.                 print data  
  36.             else:  
  37.                 print "%s error..." % line  
  38.         else:  
  39.             print line    
  40.  
  41. if __name__ == "__main__":  
  42.     ip_read() 

ip文件內容以下:ide

  
  
  
  
  1. [北京-長城寬帶-BGP]  
  2. 101.38.0.0/15  
  3. 101.40.0.0/15  
  4. 124.14.224.0/19  
  5. 124.14.64.0/18  
  6. 124.254.0.0/18  
  7. 180.88.128.0/18  
  8. 180.88.96.0/19  
  9. 180.89.64.0/19  
  10. 211.161.0.0/20  
  11. 211.161.32.0/20  
  12. 220.113.0.0/19  
  13. 220.113.32.0/20  
  14. 60.253.128.0/17  
  15. [鵬博士-BGP]  
  16. 1.93.0.0/16  
  17. 101.247.128.0/18  
  18. 113.44.0.0/16  
  19. 113.45.0.0/16  
  20. 113.46.0.0/16  
  21. 113.47.0.0/16 

結果如圖:spa

相關文章
相關標籤/搜索