javascript - 在 node.js 中使用 XPath

标签 javascript html node.js dom xpath

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

我想从 Console.WriteLine 的每个部分中提取与我的约束相匹配的 first 代码示例 - 它必须用 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')]

如果我test the XPath online ,我得到了预期的结果,is in this 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 docs ,您应该能够使用 useNamespaces 将命名空间绑定(bind)到前缀,并在您的 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);

除了将命名空间绑定(bind)到前缀,您还可以在 XPath 中使用 local-name(),但我不推荐这样做。这也涵盖了in the 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')]

关于javascript - 在 node.js 中使用 XPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47464357/

相关文章:

javascript - 固定位置的音乐播放器

node.js - Nodemon + Express 4.13.4

javascript - 要切换更多元素,但我只想切换我单击的元素

javascript - 快速路由 - 防止 app.use ('/' ) 直接访问子/嵌套路径时执行顶级路径中间件

html - 如何为 div 提供正确的对齐方式

html - 使屏幕上始终可见两个不同大小的div

javascript - Electron React 应用程序上的 Sentry/Raven - 我做错了什么?

javascript - AWS Cognito 与授权用户同步

javascript - Node.js:执行多个异步操作然后再做其他事情的最佳方式?

node.js - 尝试使用 socket.io 创建一个简单的套接字