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

news2024/10/22 6:55:00

1.搭建简单网站1

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())
<!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

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)
<!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

 

 

 

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)
<!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等请求的不同与相同,同时兼具了一定的反爬机制等知识 

 

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2220620.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Rust语言编程环境的安装

简介 Rust是一门系统编程语言,专注于安全,尤其是并发安全,支持函数式和命令式以及泛型等编程范式的多范式语言。 Rust语言的特点 系统级编程:Rust语言非常适合进行底层系统级编程,如操作系统、网络协议栈、设备驱动程序等。 内存安全:Rust使用所有权(ownership)系统来…

Scrapy | 爬取笑话网来认识继承自Spider的crawlspider爬虫类

crawlspider 1. 创建crawlspider爬虫2. 实战-爬取笑话网笑话 本篇内容旨在拓展视野和知识&#xff0c;了解crawlspider的使用即可&#xff0c;主要熟悉掌握spider类的使用 CrawlSpider 提供了一种更高级的方法来定义爬取规则&#xff0c;而无需编写大量的重复代码。它基于规则…

【功能安全】汽车功能安全个人认证证书

目录 1、证书 2、课程信息 &#x1f4d6; 推荐阅读 1、证书 汽车功能安全工程师去拿类似莱茵、SGS、南德颁发的证书&#xff0c;如下&#xff1a; 2、课程信息 一般上什么课程了&#xff0c;课程信息大概如下&#xff1a; 汽车功能安全工程师认证课 &#xff08;3天&#…

【Linux】进程的挂起状态

挂起状态的前提条件 当 内存资源严重不足 时&#xff0c;操作系统会考虑将部分进程换出到磁盘上的交换空间&#xff08;swap 分区&#xff09;。这通常发生在以下几种情况下&#xff1a; 内存不足&#xff1a; 当物理内存接近耗尽时&#xff0c;操作系统会选择将一部分暂时不需…

查缺补漏----数据结构树高总结

① 对于平衡二叉树而言&#xff0c;树高的规律&#xff1a; 高度为h的平衡二叉树的含有的最少结点数&#xff08;所有非叶节点的平衡因子均为1&#xff09;&#xff1a; n01&#xff0c;n11&#xff0c;n22 含有的最多结点数&#xff1a; (高度为h的满二叉树含有的结点数) ②…

监控内容、监控指标、监控工具大科普

在现代信息技术领域&#xff0c;监控技术扮演着至关重要的角色。它帮助我们实时了解系统、网络、应用以及环境的状态&#xff0c;确保它们的安全、稳定和高效运行。以下是对监控内容、监控指标和监控工具的详细科普。 一、监控内容 监控内容是指监控系统所关注和记录的具体信…

C++面向对象编程学习

C面向对象编程学习 前言一、C面向对象编程二、知识点学习1. 定义一个类1.1 使用struct定义1.2 使用class定义1.3 struct和class的区别 2. 类的定义方式2.1 单文件定义&#xff08;Inline Definition&#xff09;2.2 分离定义&#xff08;Separate Definition&#xff09;2.3 头…

一文2500字从0到1实现压测自动化!

大家好&#xff0c;我是小码哥&#xff0c;最近工作有点忙&#xff0c;一直在实现压测自动化的功能&#xff0c;今天来分享一下实现思路 我所在的业务线现在项目比较少了&#xff0c;所以最近一个月我都没有做业务测试&#xff0c;需求开发完后RD直接走免测就上线&#xff0c;…

利用Spring Boot实现信息化教学平台

1系统概述 1.1 研究背景 随着计算机技术的发展以及计算机网络的逐渐普及&#xff0c;互联网成为人们查找信息的重要场所&#xff0c;二十一世纪是信息的时代&#xff0c;所以信息的管理显得特别重要。因此&#xff0c;使用计算机来管理信息化在线教学平台的相关信息成为必然。开…

Ansible自动化运维管理工具

一、Ansible 1.1、自动化运维管理工具有哪些&#xff1f; 工具架构语言使用情况Ansible无clientpython 协议用ssh95%puppetC/Sruby 协议用http基本不用chefC/Sruby 协议用http基本不用saltstackC/Spython 协议用ssh5% 1.2、Ansible简介 Ansible是一个基于Py…

深度学习 简易环境安装(不含Anaconda)

在Windows上安装深度学习环境而不使用Anaconda&#xff0c;下面是一个基于pip的安装指南&#xff1a; 1. 安装Python 确保你已经安装了Python。可以从Python官网下载Python&#xff0c;并在安装时勾选“Add Python to PATH”选项。 注意&#xff0c;Python 不要安装最新版的…

期权懂|期权止损策略如何平衡风险与收益?

本期让我懂 你就懂的期权懂带大家来了解&#xff0c;期权止损策略如何平衡风险与收益&#xff1f;有兴趣的朋友可以看一下。期权小懂每日分享期权知识&#xff0c;帮助期权新手及时有效地掌握即市趋势与新资讯&#xff01; 期权止损策略如何平衡风险与收益&#xff1f; 期权止损…

如何写一个视频编码器演示篇

先前写过《视频编码原理简介》&#xff0c;有朋友问光代码和文字不太真切&#xff0c;能否补充几张图片&#xff0c;今天我们演示一下&#xff1a; 这是第一帧画面&#xff1a;P1&#xff08;我们的参考帧&#xff09; 这是第二帧画面&#xff1a;P2&#xff08;需要编码的帧&…

计算机网络—静态路由

1.0 网络拓扑结构 星型拓扑结构是一个中心&#xff0c;多个分节点。它结构简单&#xff0c;连接方便&#xff0c;管理和维护都相对容易&#xff0c;而且扩展性强。网络延迟时间较小&#xff0c;传输误差低。中心无故障&#xff0c;一般网络没问题。中心故障&#xff0c;网络就出…

MIT-OC Electrochemical Energy Systems 1-2

一、等效电路模型 L2 电化学能量转换 1. 电化学能量转换与原电池 原电池可以将不同形式的能量&#xff08;化学能、太阳能、机械压力等&#xff09;转化为电能和热能。本文档讨论了一些原电池的示例及其等效电路模型。电压源&#xff1a;特性&#xff1a;电压源的特点是提供…

从网络请求到Excel:自动化数据抓取和保存的完整指南

背景介绍 在投资和财经领域&#xff0c;论坛一直是投资者们讨论和分享信息的重要平台&#xff0c;而东方财富股吧作为中国最大的财经论坛之一&#xff0c;聚集了大量投资者实时交流股票信息。对于投资者来说&#xff0c;自动化地采集这些发帖信息&#xff0c;并进行分析&#…

ionic Capacitor 生成 Android 应用

官方文档 https://ionic.nodejs.cn/developing/android/ https://capacitorjs.com/docs/getting-started 1、创建新的 Capacitor 应用程序 空目录下面 npm init capacitor/app2、install Capacitor npm install npm start在这里插入图片描述 3、生成dist目录 npm run buil…

ChatGPT 现已登陆 Windows 平台

今天&#xff0c;OpenAI 宣布其人工智能聊天机器人平台 ChatGPT 已开始预览专用 Windows 应用程序。OpenAI 表示&#xff0c;该应用目前仅适用于 ChatGPT Plus、Team、Enterprise 和 Edu 用户&#xff0c;是一个早期版本&#xff0c;将在今年晚些时候推出"完整体验"。…

二、PyCharm基本设置

PyCharm基本设置 前言一、设置中文汉化二、设置代码字体颜色三、设置鼠标滚轮调整字体大小四、修改 PyCharm 运行内存4.1 方式一4.1 方式二 五、显示 PyCharm 运行时内存六、设置代码模版配置的参数有&#xff1a; 七、PyCharm设置背景图总结 前言 为了让我们的 PyCharm 更好用…

Axure中继器实现时间读取和修改

亲爱的小伙伴&#xff0c;在您浏览之前&#xff0c;烦请关注一下&#xff0c;在此深表感谢&#xff01; 课程主题&#xff1a;中继器实现时间读取和修改 主要内容&#xff1a;中继器内不同时间格式的向外读取&#xff0c;和向内赋值&#xff0c;实现中继器时间的修改 应用场…