我们在编程时,有时需要获取IP地址等位置信息,比如当你想向网站的用户发送登录信息时。在本文中,我们将了解如何使用Python获取IP地址。
为了获取IP地址,我们需要使用Python中的requests模块。
在使用requests模块前,我们先pip安装requests模块。
为了顺利安装外部模块,建议将pip升级到最新版。
pip install --upgrade pip
同时,以管理员模式打开命令提示符,安装requests模块。
pip install requests
![](https://img-blog.csdnimg.cn/img_convert/e52dd094c67b83acace1e2e5bc27546b.jpeg)
我们首先获取IP地址。然后,我们将使用此IP地址来获取此特定IP地址的位置信息。因此,我们将有两个函数:
get_ip()
get_location()
import requestsdef get_ip(): response = requests.get('https://api64.ipify.org?format=json').json() return response["ip"]def get_location(): ip_address = get_ip() response = requests.get(f'https://ipapi.co/{ip_address}/json/').json() location_data = { "ip": ip_address, "city": response.get("city"), "region": response.get("region"), "country": response.get("country_name") } return location_dataprint(get_location())
在本实例中,我们将只使用国家地区。所以我们创建了一个名为 location_data 的字典来保存这些信息。
#输出结果
![](https://img-blog.csdnimg.cn/img_convert/e23b2d6fad7718d92ed62bdc47975478.jpeg)