我實現了一個功能來請求“ http://cnblogs.com ”頁面。
當我使用HtmlAgilityPack替換更多的HtmlNode時,卻發生了一些混淆的事情-----它無法取代。
代碼是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;//I Use NuGet to include HtmlAgilityPack(Vs2012)
namespace CatchWebSample
{
class Program
{
public static void Main(string[] args)
{
HtmlDocument document = new HtmlDocument();
WebClient wc = new WebClient();
wc.Encoding = Encoding.GetEncoding("utf-8");
string content = wc.DownloadString("http://cnblogs.com");
document.LoadHtml(content);
string oldContent = document.DocumentNode.OuterHtml;
//here, I want to replace all xpath= //div[@class='post_item_foot'] htmlnodes
HtmlNodeCollection targetNodeCollection = document.DocumentNode.SelectNodes(@"//div[@class='post_item_foot']");
HtmlNode newHtmlNode;
if (targetNodeCollection != null && targetNodeCollection.Count > 0)
{
for (int i = 0; i < targetNodeCollection.Count; i++)
{
var targetNode = targetNodeCollection[i];
newHtmlNode = document.CreateElement("span");
newHtmlNode.InnerHtml = HtmlDocument.HtmlEncode("###### REPLACED CONTENT #########");
targetNode.ParentNode.ReplaceChild(newHtmlNode, targetNode);
}
content = document.DocumentNode.OuterHtml;
//but the result is same of the original data,why it can not replace ?
bool flag = string.Compare(oldContent, content) == 0;
}
}
}
}
我很困惑,為什麼?
replaceChild(),insertAfter()突然之間他們也停止了為我工作。
我最好的選擇是用“new html string”替換innerhtml
targetnode.innerhtml = newNodeAsString;
編輯:
HtmlAgilityPack插入值/節點時出現錯誤。由於一些緩存,使其工作更快。
這就是為什麼我拋棄它。並使用了AngleSharp 。
編輯:
2017年中期, HAP正在這裡開發。我不會回去。你也不能在HAP上創造問題。