링크 변경을 위한 HtmlAgilityPack 예제가 작동하지 않습니다.이 작업을 어떻게 수행합니까?
-
19-09-2019 - |
문제
에 대한 예 코드플렉스 이것은 :
HtmlDocument doc = new HtmlDocument();
doc.Load("file.htm");
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"])
{
HtmlAttribute att = link["href"];
att.Value = FixLink(att);
}
doc.Save("file.htm");
첫 번째 문제는 HtmlDocument입니다.문서요소 존재하지 않는다!존재하는 것은 HtmlDocument입니다.문서노드 하지만 이를 대신 사용해도 설명된 대로 href 속성에 액세스할 수 없습니다.다음 오류가 발생합니다.
Cannot apply indexing with [] to an expression of type 'HtmlAgilityPack.HtmlNode'
이 오류가 발생할 때 컴파일하려는 코드는 다음과 같습니다.
private static void ChangeUrls(ref HtmlDocument doc)
{
foreach(HtmlNode link in doc.DocumentNode.SelectNodes("//@href"))
{
HtmlAttribute attr = link["href"];
attr.Value = Rewriter(attr.Value);
}
}
업데이트: 방금 예제가 작동하도록 의도된 것이 아니라는 것을 알았습니다... 그리고 예제 코드를 읽은 후 해결책을 얻었습니다... 완료되면 나와 같은 다른 사람들이 즐길 수 있도록 내 솔루션을 게시하겠습니다.
해결책
다음은 ZIP에 포함된 샘플 코드의 일부를 기반으로 한 빠른 솔루션입니다.
private static void ChangeLinks(ref HtmlDocument doc)
{
if (doc == null) return;
//process all tage with link references
HtmlNodeCollection links = doc.DocumentNode.SelectNodes("//*[@background or @lowsrc or @src or @href]");
if (links == null)
return;
foreach (HtmlNode link in links)
{
if (link.Attributes["background"] != null)
link.Attributes["background"].Value = _newPath + link.Attributes["background"].Value;
if (link.Attributes["href"] != null)
link.Attributes["href"].Value = _newPath + link.Attributes["href"].Value;(link.Attributes["href"] != null)
link.Attributes["lowsrc"].Value = _newPath + link.Attributes["href"].Value;
if (link.Attributes["src"] != null)
link.Attributes["src"].Value = _newPath + link.Attributes["src"].Value;
}
}
제휴하지 않습니다 StackOverflow