繁体   English   中英

在 node.js 中使用 XPath

[英]Using XPath in node.js

我正在 node.js 中构建一个小文档解析器。 为了测试,我有 一个原始的 HTML 文件,它通常是在应用程序执行时从真实网站下载的。

我想从与我的约束匹配的 Console.WriteLine 的每个部分中提取第一个代码示例 - 它必须用 C# 编写。 为此,我有这个示例 XPath:

//*[@id='System_Console_WriteLine_System_String_System_Object_System_Object_System_Object_']/parent::div/following-sibling::div/pre[position()>1]/code[contains(@class,'lang-csharp')]

如果我在线测试 XPath ,我会得到预期的结果,这 在这个 Gist 中

在我的 node.js 应用程序中,我使用xmldomxpath尝试解析完全相同的信息:

var exampleLookup = `//*[@id='System_Console_WriteLine_System_String_System_Object_System_Object_System_Object_']/parent::div/following-sibling::div/pre[position()>1]/code[contains(@class,'lang-csharp')]`;
var doc = new dom().parseFromString(rawHtmlString, 'text/html');
var sampleNodes = xpath.select(exampleLookup,doc);

但是,这不会返回任何内容。

这里可能会发生什么?

这很可能是由 HTML (XHTML) 中的默认命名空间 ( xmlns="http://www.w3.org/1999/xhtml" ) 引起的。

查看xpath 文档,您应该能够使用useNamespaces将命名空间绑定到前缀,并在您的 xpath 中使用该前缀(未经测试)...

var exampleLookup = `//*[@id='System_Console_WriteLine_System_String_System_Object_System_Object_System_Object_']/parent::x:div/following-sibling::x:div/x:pre[position()>1]/x:code[contains(@class,'lang-csharp')]`;
var doc = new dom().parseFromString(rawHtmlString, 'text/html');
var select = xpath.useNamespaces({"x": "http://www.w3.org/1999/xhtml"});
var sampleNodes = xpath.select(exampleLookup,doc);

除了将命名空间绑定到前缀之外,您还可以在 XPath 中使用local-name() ,但我不建议这样做。 这也包含在 docs 中

例子...

//*[@id='System_Console_WriteLine_System_String_System_Object_System_Object_System_Object_']/parent::*[local-name()='div']/following-sibling::*[local-name()='div']/*[local-name()='pre'][position()>1]/*[local-name()='code'][contains(@class,'lang-csharp')]

有一个库xpath-html可以帮助您使用 XPath 查询 HTML,只需最少的工作和代码行。

const fs = require("fs");
const html = fs.readFileSync(`${__dirname}/shopback.html`, "utf8");

const xpath = require("xpath-html");
const node = xpath.fromPageSource(html).findElement("//*[contains(text(), 'with love')]");

console.log(`The matched tag name is "${node.getTagName()}"`);
console.log(`Your full text is "${node.getText()}"`);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM