python获取地理位置(肯定可以用)

废话不多说,直接上代码

 1 from urllib.request import urlopen
 2 my_ip = urlopen('http://ip.42.pl/raw').read()
 3 
 4 import requests
 5 import IPy
 6  
 7 def get_location(ip):
 8     url =  'https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?co=&resource_id=6006&t=1529895387942&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery110203920624944751099_1529894588086&_=1529894588088&query=%s'%ip
 9     # headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'}
10     r = requests.get(url)
11     r.encoding = r.apparent_encoding
12     html = r.text
13     c1 = html.split('location":"')[1]
14     c2 = c1.split('","')[0]
15     return c2
16  
17 def check_ip(ip):
18     try:
19         IPy.IP(ip)
20         return True
21     except Exception as e:
22         print(e)
23         return False
24  
25 if __name__ == '__main__':
26     ip = str(my_ip).strip('b')
27     ip=eval(ip)
28     print(ip)
29     if check_ip(ip):
30         print('IP位置为:',get_location(ip))
31     input()
原文地址:https://www.cnblogs.com/Ctrl-cCtrl-v/p/12905996.html