Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to obtain the location of the current equipment by python

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to achieve python to obtain the location of the current equipment, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to know about it.

I. introduction of the environment

Python version: Python3.8

Development tools: Pycharm 21

Third-party library: requests

The json library that comes with Python will also be used. Because the result returned by calling API is a message in the form of JSON or XML, at present, except for a few traditional companies that use XML to transmit information, most Internet companies use json library to transmit information.

1. Search for "Amap API", go to the official website and register your own account.

two。 Go to the console and create related applications

Click profile Picture-> Application Management-> create Application-> Select web Application-> create-> copy key

3. Enter the web service API interface

II. Code

(1) obtain local information

Query local information:

Import uuidimport socketimport requests# (1) get the native mac address def get_mac_adderss (): mac=uuid.UUID (int = uuid.getnode ()). Hex [- 12:] return ":" .join ([Mac [e: eBay 2] for e in range (0L11 L2)]) dd = get_mac_adderss () print (dd) # (2) get the local computer name myname = socket.getfqdn (socket.gethostname ()) # (3) get the native ipmyaddr = Socket.gethostbyname (myname) print (myname) print (myaddr) # (4) get the current user name def user (): import getpass user_name = getpass.getuser () return user_nameprint (user ())

We found that the above information is the intranet IP of the computer, but cannot obtain the intranet geographical location, so how can we obtain the public network IP?

Import requestsimport jsonurl = "http://httpbin.org/ip" # you can also access the address r = requests.get (url) # directly in the browser to get the returned value ip = json.loads (r.text) [" origin "] # take the value print (ip) of one of the fields

In this way, the public network IP can be printed, and then we will print the current geographical location according to the public network IP.

# send get request url = f 'http://ip-api.com/json/{ip}?fields=status,message,country,countryCode,region,regionName,city,zip,lat,lon,timezone,isp,org,as,query&lang=zh-CN'#, where the fields field is defined to accept the return parameters, but not passed Lang is the setting language, and zh-CN is Chinese. You can send the request data = json.loads (res.text) # print (res.json (), end= "\ n") print (data, end= "\ n") by res = requests.get (Chinese) #

The results are as follows:

61.52.131.62

{'status':' success', 'country':', 'countryCode':' CN', 'region':' HA', 'regionName':', 'city':' Zhengzhou', 'zip':', 'lat': 34.7599,' lon': 113.6459, 'timezone':' Asia/Shanghai', 'isp':' CNC Group CHINA169 Henan Province Network', 'org':' 'as': 'AS4837 CHINA UNICOM China169 Backbone',' query': '61.52.131.62'}

Process ended, exit code is 0

We find that all the obtained information is shown here, so how do we show only what we need? Next, we save the data we obtained in json format:

Data = json.loads (res.text) with open ('json.json','w',encoding='utf-8') as file: file.write (json.dumps (data,indent=2,ensure_ascii=False))

The results are as follows:

Then we can open the json file and read some specific data in it:

DataJson = json.load (open ('json.json', encoding='UTF-8')) # Open the json file and read all the data in it

"country"], dataJson ["regionName"], dataJson ["city"] # read the parts we need in the json file

Print (jsojsondata = [dataJson [ndata)]

The reading result is as follows:

125.41.175.176

['China', 'Henan', 'Zhengzhou']

Process ended, exit code is 0

Complete code:

Import requestsimport jsonurl = "http://httpbin.org/ip" # you can also access the address r = requests.get (url) # directly in the browser to get the returned value ip = json.loads (r.text) [" origin "] # take the value of one of the fields print (ip) # send the get request url = f 'http://ip-api.com/json/{ip}?fields=status,message,country,countryCode,region,regionName,city,zip,lat,lon,timezone,isp, Org,as,query&lang=zh-CN'# where the fields field is defined to accept the return parameters But don't pass it. Lang is the setting language, and zh-CN is Chinese You can send a request jsonobj = json.loads (res.text) # print (res.json (), end= "\ n") data = json.loads (res.text) with open ('json.json', 'walled, encoding='utf-8') as file: file.write (json.dumps (data, indent=2, ensure_ascii=False) dataJson = json.load (open (' json.json', encoding='UTF-8')) # Open json file And read all the data in jsondata = [dataJson ["country"], dataJson ["regionName"], dataJson ["city"] # read some of the print (jsondata) we need in the json file. Thank you for reading this article carefully. I hope the article "how to get the location of the current equipment" shared by the editor will be helpful to you. At the same time, I hope you will support it and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 280

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report