测试环境
- Python3.6.4
- 依赖:
requests == 2.19.1
bs4 == 4.6.3
lxml == 4.2.5
安装环境
pip3 install requests bs4 lxml
源代码
import requests
from bs4 import BeautifulSoup
url = 'http://m.ip138.com/ip.asp?ip='
kv = {'User-Agent': 'Mozilla/5.0'}
def ipQuery(ip):
"""查询IP地址并返回结果"""
link = url + str(ip)
try:
r = requests.get(link, headers=kv)
r.raise_for_status()
r.encoding = r.apparent_encoding
soup = BeautifulSoup(r.text, 'lxml')
result = soup.select('p[class="result"]')[0].string
return result
except requests.HTTPError:
print("查询失败")
if __name__ == '__main__':
ip = input("Please input a valid ip adderess: ")
print("Your result of query: ", ipQuery(ip))
测试
$ python3 ipQuery.py
Please input a valid ip adderess: 223.6.6.6
Your result of query: 本站主数据:浙江省杭州市 阿里云数据中心 阿里云