我在尝试通过html敏捷包获取数据时遇到错误为空,谁解决的
本文关键字:遇到 错误 数据 解决 获取 html 包获取 | 更新日期: 2023-09-27 18:35:49
Html 代码:
<h2 class="di-title cdo-section-title-hw">appeal</h2>
C# 代码:
string url = "http://dictionary.cambridge.org/dictionary/british/appeal";
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(url);
var infor = doc.DocumentNode.Descendants().Where(n => n.Name == "h2" && n.Attributes["class"].Value == "di-title").FirstOrDefault();
Assets.ClassHttpAgilityPack http = new Assets.ClassHttpAgilityPack();
txtword.Text = infor.FirstChild.InnerText;
txtword.Text=null;
h2
没有class="di-title"
,它有class="di-title cdo-section-title-hw"
。因此,找不到该节点。您应该检查它是否包含该类,而不是等于它。为了安全起见,您还应该检查该属性是否存在。
var infor = doc.DocumentNode.Descendants().Where(n => n.Name == "h2"
&& n.Attributes["class"] != null
&& n.Attributes["class"].Value.Contains("di-title")).FirstOrDefault();