【问题标题】:Can't get body node from html document using xpath无法使用 xpath 从 html 文档中获取正文节点
【发布时间】:2016-01-09 12:38:08
【问题描述】:

我知道这是一个愚蠢的问题,但我就是找不到问题。无法使用 xpath 从 html 文档中的正文节点获取内部文本。

我正在使用的代码:

HtmlWeb web = new HtmlWeb();

HtmlDocument doc = web.Load(String.Format(url, companyName));

HtmlNode node = doc.DocumentNode.SelectSingleNode("//body");
string code = null;
try
{
     code = node.FirstChild.InnerText;
}
catch (NullReferenceException e)
{
}

网站结构

<html>
     <body>PYRIX | preston york</body>
</html>

【问题讨论】:

  • node.InnerText 应该这样做。
  • 不。它不会,因为其中包含文本的任何节点实际上都在元素内的文本节点内。所以,firstChild 在这里我们将文本节点
  • string text = doc.DocumentNode.SelectSingleNode("//body").InnerText; 对我来说这行得通...

标签: c# html xpath


【解决方案1】:

我刚试过node.InnerText,它有效。问题一定出在您加载文档的方式上。

这行得通:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml("<html><body>PYRIX | preston york</body></html>");

var node = doc.DocumentNode.SelectSingleNode("//body");

Console.WriteLine(node.InnerText);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多