爬虫逆向-js进阶(续写,搭建网站)

1.搭建简单网站1

javascript 复制代码
from flask import Flask,render_template
import requests
import json
app = Flask('name')


# **location**的温度是**temp**度,天气状况:**desc**

@app.route('/')  # 绑定处理函数
def index_url():
    location = '101010100'
    data = get_weather(location)
    return render_template('index.html',location=data['name'],temp=data['temp'],desc=data['desc'])


def get_weather(location='101010100'):
    url = f'https://devapi.qweather.com/v7/weather/now?location={location}&key=251bac74792b4c53839b2394b5ee45cc'
    r = requests.get(url)

    # 确保请求成功
    if r.status_code == 200:
        data = json.loads(r.text)
        # 提取温度和天气状况
        temp = data['now']['temp']  # 温度
        desc = data['now']['text']  # 天气状况
        # 从 fxLink 中提取城市名称
        fx_link = data['fxLink']  # 获取 fxLink
        name = fx_link.split('/')[-1].split('-')[0]  # 提取城市名称,如 'beijing'
        # 构造返回的天气信息字典
        weather = {'name': name, 'temp': temp, 'desc': desc}
        return weather


if __name__ == '__main__':
    # app.run(host='127.1.1.0', port=9999)
    print(get_weather())
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>查询天气预报</title>
</head>
<body>
<h1>{{location}}的温度是{{temp}}度,天气状况:{{desc}}</h1>
<script src="static\jquery-1.10.1.min.js"></script>
<script>
    $(function (){
        alert('已经加载jQuery')
    })
</script>
</body>
</html>

2.搭建简单网站2

javascript 复制代码
from flask import Flask,render_template,request
import requests
import json
app = Flask('name')


# **location**的温度是**temp**度,天气状况:**desc**

@app.route('/')  # 绑定处理函数
def index_url():
    location = '101010100'
    data = get_weather(location)
    return render_template('index.html',location=data['name'],temp=data['temp'],desc=data['desc'])

@app.route('/get_data')
def get_data():
    loc = request.args.get('loc')
    ua = requests.headers.get('User-Agent')
    token = requests.cookies.get('token')
    data = ''
    if 'python' in ua:
        msg = '检测到自动化程序'
    elif not token or token != 'abc':
        msg = 'Token参数错误'
    elif not loc:
        msg = '查询参数错误'
    else:
        data = get_weather(loc)
        msg = '请求正常'



    sender_data = {'msg':msg,'data':data}
    sender_str = json.dumps(sender_data)
    return sender_str

@app.route('/post_data', methods=['POST'])
def post_data():
    # loc = request.form.get('loc')  # 获取数据
    loc = request.json.get('loc') # payload
    data = get_weather(loc)
    msg = '请求正常'
    sender_data = {'msg': msg, 'data': data}
    sender_str = json.dumps(sender_data)
    return sender_str


def get_weather(location='101010100'):
    url = f'https://devapi.qweather.com/v7/weather/now?location={location}&key=251bac74792b4c53839b2394b5ee45cc'
    r = requests.get(url)

    # 确保请求成功
    if r.status_code == 200:
        data = json.loads(r.text)
        # 提取温度和天气状况
        temp = data['now']['temp']  # 温度
        desc = data['now']['text']  # 天气状况
        # 从 fxLink 中提取城市名称
        fx_link = data['fxLink']  # 获取 fxLink
        name = fx_link.split('/')[-1].split('-')[0]  # 提取城市名称,如 'beijing'
        # 构造返回的天气信息字典
        weather = {'name': name, 'temp': temp, 'desc': desc}
        return weather


if __name__ == '__main__':
    app.run(host='127.1.1.0', port=9999)
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>查询天气预报</title>
</head>
<body>
<h1>{{ location }}的温度是{{ temp }}度,天气状况:{{ desc }}</h1>
<script src="static\jquery-1.10.1.min.js"></script>
<script>
    let date = new Date(); // 获取当前时间
    console.log(date.toString());
    date.setTime(date.getTime() + 1000 * 1000); // 单位为毫秒,设置几秒后删除cookie,这里为1000秒
    // 使用方法打开浏览器页面,查看cookie值,最后把下面设置cookie和时间的(下面这行)注释掉,静等两分钟查看浏览器即可。
    document.cookie = `token=abc;expires=${date.toString()}`; // 给添加的cookie值加上日期

    $(function () {
        $('#b1').click(function () {
            var query = $('#t1').val()
            $.ajax({
                // url: `/get_data?loc=${query}`,
                url: '/post_data',
                method: 'post',
                data: JSON.stringify({  //
                    loc: query
                }),
                contentType: 'Application/json',
                success: function (data) {
                    weather_data = JSON.parse(data) //python json.loads
                    loc = weather_data['data']['name']
                    temp = weather_data['data']['temp']
                    desc = weather_data['data']['desc']
                    display_h1 = `${loc}的温度是${temp}度,天气状况:${desc}`
                    $('h1').text(display_h1)
                }
            })
        })
    })
</script>
<br><br><input id="t1" placeholder="请输入要查询的城市名字">
<button id="b1">查询天气预报</button>
</body>
</html>

3.搭建简单网站3

javascript 复制代码
from flask import Flask,render_template,request
import requests
import json
app = Flask('name')


# **location**的温度是**temp**度,天气状况:**desc**

@app.route('/')  # 绑定处理函数
def index_url():
    location = '101010100'
    data = get_weather(location)
    return render_template('index.html',location=data['name'],temp=data['temp'],desc=data['desc'])

@app.route('/get_data')
def get_data():
    loc = request.args.get('loc')
    ua = requests.headers.get('User-Agent')
    token = requests.cookies.get('token')
    data = ''
    if 'python' in ua:
        msg = '检测到自动化程序'
    elif not token or token != 'abc':
        msg = 'Token参数错误'
    elif not loc:
        msg = '查询参数错误'
    else:
        data = get_weather(loc)
        msg = '请求正常'

    sender_data = {'msg':msg,'data':data}
    sender_str = json.dumps(sender_data)
    return sender_str

@app.route('/post_data', methods=['POST'])
def post_data():
    # loc = request.form.get('loc')  # 获取数据
    loc = request.json.get('loc') # payload
    data = get_weather(loc)
    msg = '请求正常'
    sender_data = {'msg': msg, 'data': data}
    sender_str = json.dumps(sender_data)
    return sender_str

# @app.route('/axios')
# def axios():
#     return '这是一个axios的请求数据'


def get_weather(location='101010100'):
    url = f'https://devapi.qweather.com/v7/weather/now?location={location}&key=251bac74792b4c53839b2394b5ee45cc'
    r = requests.get(url)

    # 确保请求成功
    if r.status_code == 200:
        data = json.loads(r.text)
        # 提取温度和天气状况
        temp = data['now']['temp']  # 温度
        desc = data['now']['text']  # 天气状况
        # 从 fxLink 中提取城市名称
        fx_link = data['fxLink']  # 获取 fxLink
        name = fx_link.split('/')[-1].split('-')[0]  # 提取城市名称,如 'beijing'
        # 构造返回的天气信息字典
        weather = {'name': name, 'temp': temp, 'desc': desc}
        return weather


if __name__ == '__main__':
    app.run(host='127.1.1.0', port=9999)
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>查询天气预报</title>
</head>
<body>
<h1>{{ location }}的温度是{{ temp }}度,天气状况:{{ desc }}</h1>
<script src="static\jquery-1.10.1.min.js"></script>
<script>
    let date = new Date(); // 获取当前时间
    console.log(date.toString());
    date.setTime(date.getTime() + 1000 * 1000); // 单位为毫秒,设置几秒后删除cookie,这里为1000秒
    // 使用方法打开浏览器页面,查看cookie值,最后把下面设置cookie和时间的(下面这行)注释掉,静等两分钟查看浏览器即可。
    document.cookie = `token=abc;expires=${date.toString()}`; // 给添加的cookie值加上日期

    $(function () {
        $('#b1').click(function () {
            var query = $('#t1').val()
            $.ajax({
//              url: `/get_data?loc=${query}`,
                url: '/post_data',
                method: 'post',
                data: JSON.stringify({  //
                    loc: query
                }),
                contentType: 'Application/json',
                success: function (data) {
                    weather_data = JSON.parse(data) //python json.loads
                    loc = weather_data['data']['name']
                    temp = weather_data['data']['temp']
                    desc = weather_data['data']['desc']
                    display_h1 = `${loc}的温度是${temp}度,天气状况:${desc}`
                    $('h1').text(display_h1)
                }
            })
        })
    })
</script>
{#<script src="static/axios.min.js"></script>#}
{#<script>#}
{#    axios.interceptors.request.use(function (config) {#}
{#        console.log('拦截发送数据', config)#}
{#        //加密处理#}
{#        return config#}
{#    })#}
{##}
{#    axios.interceptors.response.use(function (config) {#}
{#        console.log('拦截收到的数据', config)#}
{#        //解密处理#}
{#        return config#}
{#    })#}
{##}
{#    window.onload = function () {#}
{#        document.getElementById('b1').addEventListener('click', function () {#}
{#            axios.get('/axios').then(function (res) {#}
{#                console.log(res.data)#}
{#            })#}
{#        })#}
{#    }#}
{#</script>#}
<br><br><input id="t1" placeholder="请输入要查询的城市名字">
<button id="b1">查询天气预报</button>
</body>
</html>

4.简单网站最终呈现:

此网页可以进行爬虫爬取数据,对比发现get,post等请求的不同与相同,同时兼具了一定的反爬机制等知识

查询一下信阳城市天气,得到结果:

相关推荐
qystca19 分钟前
洛谷 B3637 最长上升子序列 C语言 记忆化搜索->‘正序‘dp
c语言·开发语言·算法
薯条不要番茄酱19 分钟前
数据结构-8.Java. 七大排序算法(中篇)
java·开发语言·数据结构·后端·算法·排序算法·intellij-idea
今天吃饺子24 分钟前
2024年SCI一区最新改进优化算法——四参数自适应生长优化器,MATLAB代码免费获取...
开发语言·算法·matlab
努力进修28 分钟前
“探索Java List的无限可能:从基础到高级应用“
java·开发语言·list
Ajiang28247353042 小时前
对于C++中stack和queue的认识以及priority_queue的模拟实现
开发语言·c++
ggdpzhk2 小时前
VUE:基于MVVN的前端js框架
前端·javascript·vue.js
幽兰的天空2 小时前
Python 中的模式匹配:深入了解 match 语句
开发语言·python
小曲曲3 小时前
接口上传视频和oss直传视频到阿里云组件
javascript·阿里云·音视频
学不会•4 小时前
css数据不固定情况下,循环加不同背景颜色
前端·javascript·html
EasyNTS5 小时前
H.264/H.265播放器EasyPlayer.js视频流媒体播放器关于websocket1006的异常断连
javascript·h.265·h.264