HTMLAgilityPack 라이브러리에 대한 좋은 소식을 들었으므로 시도해 보겠다고 생각했지만 성공은 전혀 없었습니다. 나는 이것을 몇 달 동안 알아 내려고 애썼다. 아무리해도 내가이 코드가 null이 아닌 다른 것을 줄 수는 없다. 나는이 예제 ( http://www.c-sharpcorner.com/uploadfile/9b86d4/getting-started-with-html-agility-pack/ )를 따라했지만, 같은 결과를 얻지 못했고 그 이유를 설명 할 수 없었다.
파일을로드 한 다음 SelectNodes를 실행하여 모든 하이퍼 링크를 선택하려고 시도하지만 항상 빈 목록을 반환합니다. 모든 종류의 노드 (div, p, a, 모든 것과 아무것도)를 선택하려고 시도했으며 항상 빈 목록을 반환합니다. doc.Descendants를 사용해 보았습니다. 다른 소스 파일을 사용하여 로컬 및 웹에서 시도 했으므로 실제 결과가 반환되지 않습니다.
나는 중요한 것을 간과 했음에 틀림 없다. 그러나 나는 그것이 무엇인지 알 수 없다. 나는 무엇을 놓칠 수 있 었는가?
암호:
public string GetSource()
{
try
{
string result = "";
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
if (!System.IO.File.Exists("htmldoc.html"))
throw new Exception("Unable to load doc");
doc.LoadHtml("htmldoc.html"); // copied locally to bin folder, confirmed it found the file and loaded it
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a"); // Always returns null, regardless of what I put in here
if (nodes != null)
{
foreach (HtmlNode item in nodes)
{
result += item.InnerText;
}
}
else
{
// Every. Single. Time.
throw new Exception("No matching nodes found in document");
}
return result;
}
catch (Exception ex)
{
return ex.ToString();
}
}
소스 HTML 파일 'htmldoc.html'은 다음과 같이 사용합니다.
<html>
<head>
<title>Testing HTML Agility Pack</title>
</head>
<body>
<div id="div1">
<a href="div1-a1">Link 1 inside div1</a>
<a href="div1-a2">Link 2 inside div1</a>
</div>
<a href="a3">Link 3 outside all divs</a>
<div id="div2">
<a href="div2-a1">Link 1 inside div2</a>
<a href="div2-a2">Link 2 inside div2</a>
</div>
</body>
</html>