Python腳本查詢IP的地理位置

版本:Python2.7.9

模塊:requests、bs4

這裏用的是bs4解釋網頁,也可以用正則,少安裝模塊


# coding:utf-8
# 使用ip138查詢目標ip的位置信息 20170303


import sys
reload(sys), sys.setdefaultencoding('utf-8')
import requests
from bs4 import BeautifulSoup

URL = 'http://www.ip138.com/ips138.asp?ip=%s&action=2'
HEADERS = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'}

def ip_dz(ip):
    url_html = requests.get(URL % ip, headers=HEADERS).content
    data = BeautifulSoup(url_html, "html.parser")
    name = data.find('ul', attrs={'class': 'ul1'}).find('li')
    data_name = str(name.string).split(':')[1]
    data_utf_8 = data_name.decode('utf8')
    return data_utf_8

if __name__ == "__main__":
    data_sun = ip_dz('119.29.29.29')
    print '*' * 50
    print data_sun


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章