更新记录

1.0.0(2023-07-29)

uniapp爬取网页html,使用cheerio解析内容,欢迎使用


平台兼容性

Vue2 Vue3
App 快应用 微信小程序 支付宝小程序 百度小程序 字节小程序 QQ小程序
app-vue app-nvue
钉钉小程序 快手小程序 飞书小程序 京东小程序
H5-Safari Android Browser 微信浏览器(Android) QQ浏览器(Android) Chrome IE Edge Firefox PC-Safari

功能说明:

小程序中操作不了dom,所以这里使用第三方模块cheerio

如果你的项目中没有package.json的话,请先初始化npm init

安装 npm install cheerio

爬取效果,见图

cheerio-github

示例

<template>
    <view>
        <view class="title">{{text}}</view>
        <view class="content">
            <rich-text :nodes="con"></rich-text>
        </view>
    </view>
</template>

<script>
    import { cheerio } from './cheerio.js'
    export default {
        data() {
            return {
                text:'',
                con:'',
                data:[]
            }
        },
        onLoad(){
            this.getHtml()

        },
        methods: {
            getHtml(){
                // const $ = cheerio.load('<h2 class="title">Hello world</h2>');
                // $('h2.title').text('Hello there!');
                // $('h2').addClass('welcome');
                // this.text = $.html();

                let that = this
                uni.request({
                    url:'https://www.xiaoxues.com/yuwen/1910.html',
                    success(res) {
                        //1、_useHtmlParser2:解决parse创建dom报错
                        //2、decodeEntities:解决html方法被编码问题
                        const $ = cheerio.load(res.data, { _useHtmlParser2: true,decodeEntities: false })

                        const title = $('.title');
                        that.text = title[0].children[0].data

                        const content = $('.content');
                        that.con = content.html()
                    }
                })
            }
        }
    }
</script>

<style>
.title{
    padding: 30rpx ;
}
.content{
    padding: 30rpx;
}
</style>

隐私、权限声明

1. 本插件需要申请的系统权限列表:

2. 本插件采集的数据、发送的服务器地址、以及数据用途说明:

3. 本插件是否包含广告,如包含需详细说明广告表达方式、展示频率:

许可协议

MIT协议

使用中有什么不明白的地方,就向插件作者提问吧~ 我要提问