Python爬取IP归属地信息及各个地区天气信息

一、实现样式


二、核心点

1、语言:Python、HTML,CSS

2、python web框架 Flask

3、三方库:requests、xpath

4、爬取网站:https://ip138.com/

5、文档结构

三、代码

ipquery.py

python 复制代码
import requests
from lxml import etree
# 请求user-agent
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'}

def getIpInfo(ip):
    ipurl = f"https://ip138.com/iplookup.php?ip={ip}&action=2"
    res = requests.get(ipurl,headers = headers)
    e = etree.HTML(res.text)
    ip = e.xpath("//div[@class='caption']//h1//text()")
    ipinfo = e.xpath("//div[@class='table-box']//tbody//tr//td[2]//text()")
    ipinfo.append(ip[0])
    return ipinfo

searchWeather.py

python 复制代码
import requests
from lxml import etree,html
import re

# 请求user-agent
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'}
def getWeather(location):
    weatherUrl = f"https://www.wentian123.com/search/?location={location}"
    res = requests.get(weatherUrl,headers = headers)
    e = etree.HTML(res.text)
    weather = e.xpath("//table//tbody//td//text()")
    
    #处理数据
    # 去除'\n'
    weathernew = [x.strip() for x in weather]
    # 去掉空字符串''
    while ''  in weathernew:
        weathernew.remove('')
    # print(weathernew)
    # 数据分组 6个一组
    weatherInfo = [weathernew[i:i+6] for i in range(0,len(weathernew),6)]
    return weatherInfo

query.py

python 复制代码
from flask import Flask,render_template,request

from ipquery.ipquery import getIpInfo
from searchWeather.seachWeather import getWeather
app = Flask(__name__)

# 主页
@app.route('/')
def index():
    return render_template('index.html',weather = [],ipinfo = [])

# ip地址查询
@app.route('/ipquery')
def ipquery():
    ip = request.args.get('ip')
    ipinfo = getIpInfo(ip)
    # print(ipinfo[1])
    return render_template('index.html',ipinfo = ipinfo,weather = [])

# 天气查询
@app.route('/weather')
def getweather():
    location = request.args.get('location')
    # print(location)
    weather = getWeather(location)
    # print(weather)
    return render_template('index.html',weather = weather,ipinfo = [])

if __name__ == '__main__':
    app.run(port=5000, debug=True)

index.html

javascript 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <title>查询网站</title>
</head>
<style>
    * {
        margin: 0 auto;
        padding: 0 auto;
        /* display: flex; */
    }
    
    .public {
        box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
        margin: 0 auto;
        width: fit-content;
        padding: 40px 60px;
        text-align: center;
        margin-top: 20px;
    }
</style>

<body style="margin: 0 auto;">
    <!-- ip查询 -->
    <div>
        <div class="public">
            <h3>IP归属地查询</h3>
            </h3>
            </h3>
            <form class="form-inline" action="/ipquery">
                <div class="form-group">
                    <label for="exampleInputEmail2">IP地址</label>
                    <input type="text" class="form-control" name="ip" placeholder="请输入需要查询的IP地址" style="width: 300px;">
                </div>
                <button type="submit" class="btn btn-primary">查询</button>
            </form>
            <table class="table table-bordered" style="width: 100%;margin-top: 20px;">
                <tr>
                    <th style="text-align: center;">IP地址</th>
                    <th style="text-align: center;">ASN归属地</th>
                    <th style="text-align: center;">运营商</th>
                </tr>
                {% if ipinfo != [] %}
                <tr>
                    <td>{{ipinfo[-1]}}</td>
                    <td>{{ipinfo[0]}}</td>
                    <td>{{ipinfo[1]}}</td>
                </tr>
                {% endif %}

            </table>
        </div>

        <!-- 天气查询 -->
        <div class="public">
            <form class="form-inline" action="/weather">
                <div class="form-group">
                    <input type="text" class="form-control" name="location" placeholder="请输入市区县名称、区号或者邮政" style="width: 300px;">
                </div>
                <button type="submit" class="btn btn-primary">查询</button>
            </form>
            <table class="table table-bordered table-striped table-hover" style="width: 100%;margin-top: 20px;">
                {% if weather != [] %}
                <tbody>
                    {% for i in weather %}
                    <tr>
                        <td colspan="4" style="font-size: 16px;">{{i[0]}}</td>
                    </tr>
                    <tr>
                        <td>{{i[1]}}{{i[2]}}</td>
                        <!-- <td>{{i[2]}}</td> -->
                        <td>{{i[3]}}</td>
                        <td>{{i[4]}}</td>
                        <td>{{i[5]}}</td>
                    </tr>
                    {% endfor %}
                </tbody>
                {% endif %}
        </div>
    </div>
</body>
</html>

四、总结

初学python,很多代码写的很冗余,不够简洁,还有一些逻辑没有处理好,感谢贵网站 信息查询网站 提供的接口数据,里面还有很多类型的查询,这边就简单写了两个查询方法的爬虫,继续加油!!!

相关推荐
励志不掉头发的内向程序员3 分钟前
STL库——string(类函数学习)
开发语言·c++
一百天成为python专家31 分钟前
Python循环语句 从入门到精通
开发语言·人工智能·python·opencv·支持向量机·计算机视觉
Sunhen_Qiletian34 分钟前
朝花夕拾(五)--------Python 中函数、库及接口的详解
开发语言·python
hqwest43 分钟前
C#WPF实战出真汁07--【系统设置】--菜品类型设置
开发语言·c#·wpf·grid设计·stackpanel布局
前路不黑暗@1 小时前
C语言:操作符详解(二)
c语言·开发语言·经验分享·笔记·学习·学习方法·visual studio
三年呀1 小时前
标题:移动端安全加固:发散创新,筑牢安全防线引言:随着移动互联网
网络·python·安全
上海云盾第一敬业销售1 小时前
小程序被爬虫攻击,使用waf能防护吗?
爬虫·小程序
深盾科技2 小时前
Kotlin Data Classes 快速上手
android·开发语言·kotlin
zzywxc7872 小时前
详细探讨AI在金融、医疗、教育和制造业四大领域的具体落地案例,并通过代码、流程图、Prompt示例和图表等方式展示这些应用的实际效果。
开发语言·javascript·人工智能·深度学习·金融·prompt·流程图
tan77º2 小时前
【项目】分布式Json-RPC框架 - 项目介绍与前置知识准备
linux·网络·分布式·网络协议·tcp/ip·rpc·json