Javascript 在node.js中使用XPath

Javascript 在node.js中使用XPath,javascript,html,node.js,dom,xpath,Javascript,Html,Node.js,Dom,Xpath,我正在node.js中构建一个小文档解析器。为了测试,我有,这通常是从真正的网站下载时,应用程序执行 我想从Console.WriteLine的每个部分提取与我的约束匹配的第一个代码示例-它必须用C#编写。为此,我提供了以下示例XPath: //*[@id='System_Console_WriteLine_System_String_System_Object_System_Object_System_Object_']/parent::div/following-sibling::div/p

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

我想从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')]
如果我,我会得到预期的结果

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

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);
但是,这不会返回任何内容


这可能是怎么回事?

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

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

您也可以在XPath中使用
local-name()
,而不是将名称空间绑定到前缀,但我不建议这样做。这也包括在内

例如

//*[@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,只需最少的工作量和代码行

const fs=require(“fs”);
consthtml=fs.readFileSync(`${uu dirname}/shopback.html`,“utf8”);
constxpath=require(“XPathHTML”);
const node=xpath.fromPageSource(html).findElement(“//*[contains(text(),'with love')]”);
log(`匹配的标记名是“${node.getTagName()}”`);
log(`您的全文是“${node.getText()}”`);
//*[@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')]