版本: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