【发布时间】:2017-04-11 01:09:34
【问题描述】:
我目前正在尝试根据其上方的标题解析来自 HTML 文档的链接,但无论我尝试什么,程序都无法找到它。 这是我的方法不起作用:
public string findMajorURL(string collegeURL, string major)
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(collegeURL);
var root = doc.DocumentNode;
var htmlNodes = root.Descendants();
//Find html node containing the major heading
foreach(HtmlNode node in htmlNodes)
{
if (node.InnerText == major)
{
HtmlNode target = node.NextSibling;
List<string> links = target.Descendants("a").Select(a => a.Attributes["href"].Value).ToList();
return links.First()+ "__IT WORKED__";
}
}
return "Major not found";
}
这就是我试图解析的 HTML:
<div style="padding-left: 20px">
<h3 id="ent1629">Biological Sciences </h3>
<a href="preview_entity.php?catoid=5&ent_oid=1629&returnto=818">Go to information for this department.</a>
<br>
<p>...</p>
<div id="data_c_1629" style="display: none">...</div>
<!--script language="javascript">hideshow(data_c_1630)</script-->
用户输入的专业应该与标题生物科学相匹配。根据标题,我想获得 under 的链接,在本例中为 preview_entity.php?catoid=5&ent_oid=1629&returnto=818
警告:我不能将 XPath 与我拥有的 Visual Studio 版本一起使用,所以我假设以某种方式使用 LINQ 将是最好的方法,但我再次不确定。
编辑 事实证明,内部文本与专业不匹配,但是,我看不出这怎么可能,因为我直接从 html 代码中获取了它。有什么想法吗?
【问题讨论】:
标签: c# html linq html-agility-pack