一、requests模块(python3)
import requests
def get_public_ip():
response = requests.get('http://ip-api.com/json')
if response.status_code == 200:
data = response.json()
if data['status'] == 'success':
return data['query']
return None
print(get_public_ip())
二、urllib模块(python3)
import urllib.request
def get_ip():
url = "https://api.ipify.org"
response = urllib.request.urlopen(url)
return response.read().decode()
print(get_ip())
三、urllib2模块(Python2)
import urllib2 as request
url = "http://ifconfig.me/ip"
req = request.Request(url=url)
res = request.urlopen(req)
ip = res.read().decode()
print(ip)