请用Python给我写一个程序,要求:1,程序为中文语言,使用www.ip138.com网站查询;2,用户可通过输入IPv4地址,在点击回车键后查询输入IPv4地址的经纬度信息,经纬度信息要精确到分、秒,并把查询到的经纬度信息以文本的形式呈现在控制台上。
时间: 2023-06-09 21:06:14 浏览: 32
好的,根据您的要求,您可以尝试运行以下Python程序:
```python
import requests
from bs4 import BeautifulSoup
def get_ip_location(ip_address):
'''通过ip138网站查询给定IP地址的经纬度信息'''
url = f'http://www.ip138.com/ips1388.asp?ip={ip_address}&action=2'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
response = requests.get(url, headers=headers)
response.encoding = 'gbk' # 设置网页编码为gbk
soup = BeautifulSoup(response.text, 'html.parser')
result = soup.find('ul', class_='ul1').find_all('li')[0].text.split(':')[-1] # 获取经纬度信息
return result
if __name__ == '__main__':
ip_address = input("请输入IPv4地址:")
location = get_ip_location(ip_address)
print("查询到的经纬度信息:%s" % location)
```
该程序可通过获取输入的IPv4地址,利用http://www.ip138.com/网站查询该IP地址的经纬度信息,并在控制台上以文本形式输出。您可以尝试运行此程序,如果有不明白的地方可以随时向我提问。