You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将WebView2文档加载到HtmlAgilityPack?解析节点返回null求助

问题原因与解决方案

核心问题

ExecuteScriptAsync返回的是JSON序列化后的字符串,并非原始HTML内容。比如你获取到的dom实际是带转义字符的JSON格式(例如<div>test</div>会变成"\"<div>test</div>\""),直接传给LoadHtml会导致HtmlAgilityPack解析出异常的DOM结构,自然无法匹配到//div节点。

解决步骤

  1. 先将JSON字符串反序列化为原始HTML
    使用JSON库把转义后的字符串还原成真实的HTML内容。
  2. 再加载到HtmlAgilityPack进行解析

修改后的代码示例

方案1:使用Newtonsoft.Json(需安装NuGet包Newtonsoft.Json)

string dom = await webView21.CoreWebView2.ExecuteScriptAsync("document.body.outerHTML");
// 反序列化还原原始HTML
string rawHtml = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(dom);

HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument();
// 可选:开启HtmlAgilityPack的修复选项,提升容错性
htmlDocument.OptionFixNestedTags = true;
htmlDocument.OptionAutoCloseOnEnd = true;
htmlDocument.LoadHtml(rawHtml);

var divs = htmlDocument.DocumentNode.SelectNodes("//div");
if (divs == null)
    System.Diagnostics.Debug.WriteLine("divs is null");
else
    System.Diagnostics.Debug.WriteLine($"Found {divs.Count} divs");

方案2:使用System.Text.Json(.NET Core/.NET 5+内置)

string dom = await webView21.CoreWebView2.ExecuteScriptAsync("document.body.outerHTML");
// 反序列化还原原始HTML
string rawHtml = System.Text.Json.JsonSerializer.Deserialize<string>(dom);

HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument();
htmlDocument.LoadHtml(rawHtml);

var divs = htmlDocument.DocumentNode.SelectNodes("//div");
if (divs == null)
    System.Diagnostics.Debug.WriteLine("divs is null");
else
    System.Diagnostics.Debug.WriteLine($"Found {divs.Count} divs");

验证说明

反序列化后,rawHtml就是和页面DOM一致的原始HTML字符串,此时HtmlAgilityPack能正确解析结构,//div就能匹配到对应的节点。

内容的提问来源于stack exchange,提问作者Pan ache

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:00:25