#encode:utf-8 import time import urllib.request import json f = "ip.txt" def ip_location(ip): url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={%s}&co=&resource_id=6006&t=1529809984888&ie=utf8&oe=gbk&format=json&tn=baidu" % (ip) try: data = urllib.request.urlopen(url ).read() usr_data = data.decode("gbk","ignore") datadict=json.loads(usr_data) # print(datadict) addr = (datadict['data'][0])["location"] ip_name = (datadict['data'][0])["origip"] print (addr+":"+ip_name) except Exception as e: print(e) if __name__ =="__main__": with open(f) as f: for i in f: ip_location(i.strip())