Python3爬蟲查詢IP地址歸屬地

測試環境

  • Python3.6.4
  • 依賴:
    requests == 2.19.1
    bs4 == 4.6.3
    lxml == 4.2.5

安裝環境

pip3 install requests bs4 lxml

源代碼

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
#   @Version: v1.0
#   @license: Apache Licence
#   @File Name: ipQuery.py
#   @Description: 查詢IP地址歸屬地
#   @Author: pengshp <[email protected]>
#   @Date: 2018/10/16 0016
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

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:  本站主數據:浙江省杭州市 阿里雲數據中心 阿里雲
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章