【问题标题】:Nodejs xpath selector on xhtml not workingxhtml上的Nodejs xpath选择器不起作用
【发布时间】:2019-07-18 16:41:40
【问题描述】:

我有一个简单但格式不是很好的 html 页面,其中包含所有错误:

<HTML>
<head>
  <title>Official game sheet</title>
</head>
<body class="sheet">
</BODY>
</HTML>

尝试在从此 html 解析的文档上应用 xpath //title。

const document = parse5.parse(xmlString);
const xhtml = xmlser.serializeToString(document);
const doc = new dom().parseFromString(xhtml);
const select = xpath.useNamespaces({
  "x": "http://www.w3.org/1999/xhtml"
});
const nodes = select("//title", doc);
console.log(nodes);

尝试了from here 的解决方案,但没有成功。返回的节点列表为空。

Here you can see the problem.

【问题讨论】:

    标签: node.js xpath


    【解决方案1】:

    给你@neptune,你不需要 parse5 或 xmlser,只需要 xpath 和 xmldom。

    var xpath = require('xpath');
    var dom = require('xmldom').DOMParser;
    var xmlString = `
    <HTML>
    <head>
      <title>Official game sheet</title>
      <custom>Here we are</custom>
    <body class="sheet">
    </BODY>
    </HTML>`;
    
    //const document = parse5.parse(xmlString);
    //const xhtml = xmlser.serializeToString(document);
    const doc = new dom().parseFromString(xmlString);
    const nodes = xpath.select("//custom", doc);
    //console.log(document);
    
    console.log(nodes[0].localName + ": " + nodes[0].firstChild.data);
    console.log("Node: " + nodes[0].toString());
    

    【讨论】:

      【解决方案2】:

      请更正这些行以获得标题

      const nodes = select("//x:title//text()", doc);
      console.log(nodes[0].data)
      

      【讨论】:

        猜你喜欢
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多