小程序开发-使用xpath解析网页html中的数据

最新有个微信小程序的开发需求,需要从网页中提取一些元素信息,获取有效数据

1. 了解到微信小程序里面不能直接操作dom元素,所以我们需要使用一些其他的npm包

2. 经过查到各方面的文档,最新决定用xpath来实现对应功能

a. 先安装对应的npm包,安装步骤见上一篇文章 小程序使用npm包
b. 我们安装了如下的npm包, https://github.com/yaronn/xpath.js
c. 安装完后后,我们用测试代码验证

    var select = require('xpath.js')
      , dom = require('xmldom').DOMParser

    var xml = "<book><title>Harry Potter</title></book>"
    var doc = new dom().parseFromString(xml)    
    var nodes = select(doc, "//title")
    console.log(nodes[0].localName + ": " + nodes[0].firstChild.data)
    console.log("node: " + nodes[0].toString())

输出结果如下:

title: Harry Potter
index.js? [sm]:78 node: <title>Harry Potter</title>

这样我们就可以解析html数据了

原文地址:https://www.cnblogs.com/limaostudio/p/13595981.html