【python爬虫】爬取ip138信息(随机调用User-Agent)

本模块为IP溯源单线程获取ip138信息的模块。

效果图:

在这里插入图片描述

代码:

import re
import requests
from fake_useragent import UserAgent

def get_ip138html(ip):
   # 加入Useer-Agent否则无法获取响应,这里产生随机UserAgent,防止基于User-Agent的反爬
    User_Agent = UserAgent().random
    headers = {
        'User-Agent': User_Agent
    }
    url = 'https://www.ip138.com/iplookup.asp?ip=' + ip + '&action=2'
    # 编码解码的方式防止乱码
    html = requests.post(url, headers=headers).text.encode('raw_unicode_escape').decode('gbk')
    return html


def dig_ip138_information(html):
    # 获得ip段
    rule1 = re.compile(r'"iP段":"(.*)", "兼容')
    # 观察响应发现其他信息都储存在一个字典中,利用正则获取字典
    rule2 = re.compile(r'"ip_c_list":\[(.*)], "zg"')
    # 从html源码中正则获取信息
    # result1为ip的网段,result2为其他信息
    result1 = rule1.search(html).group(1)
    result2 = rule2.search(html).group(1)
    # 将获取到的字典字符串转换为python字典
    ip_information_dict = eval(result2)
    # 由于已经获取到网段,且经测试idc均无返回值,删除这三对键值
    ip_information_dict.pop('begin')
    ip_information_dict.pop('end')
    ip_information_dict.pop('idc')
    # 增加网段的键值对
    ip_information_dict['segment'] = result1
    # 将国家省城市键合并为place字符串
    place = ip_information_dict['ct'] + ip_information_dict['prov'] + ip_information_dict['city'] + ip_information_dict[
        'area']
    # 删除这些键值
    ip_information_dict.pop('ct')
    ip_information_dict.pop('prov')
    ip_information_dict.pop('city')
    ip_information_dict.pop('area')
    # 将place键值增加到字典
    ip_information_dict['place'] = place
    # 返回字典
    return ip_information_dict


if __name__ == '__main__':
    ip = '36.110.116.43'
    # 获得ip138的页面
    ip138_html = get_ip138html(ip)
    # 爬取信息,并返回一个字典
    ip_information = dig_ip138_information(ip138_html)
    print(ip_information)
{'yunyin': '电信', 'net': '', 'segment': '36.110.87.0 - 36.110.146.255', 'place': '中国北京市北京市'}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值