IP地址地理位置接口(python版)

前言

不会爬虫的数据分析师是不合格的码农。

解决问题

批量获取IP地址的地理位置

代码

# !/usr/bin/env python
# -*- coding:utf8 -*-
# create on 16/4/1
__author__ = 'syp'

from pyquery import PyQuery as pq
import urllib2
import re
import sys

reload(sys)
sys.setdefaultencoding("utf8")


def paser(ip):
    '''
    IP位置接口
    :param ip: 输入IP地址
    :return: 返回IP地理位置、公司信息或运营商信息
    '''
    url = "http://www.ip138.com/ips1388.asp?ip=%s&action=2" % ip
    page = urllib2.urlopen(url)
    text = unicode(page.read(), "gb2312")  # 根据网址原始的编码,对内容进行重新编码
    content = pq(text)
    lines = content('''ul[class="ul1"]''')
    reg = ur"^本站主数据:(.*) 参考数据.*$"
    reg_q = re.compile(reg)
    for ele in lines:
        line = pq(ele).text()
        res = reg_q.findall(line)
        if res:
            return res[0]

if __name__ == '__main__':
    ip = "121.10.104.107"
    print ip, paser(ip)

运行结果

121.10.104.107 广东省湛江市  电信
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值