Implemento una funzionalità per richiedere la pagina " http://cnblogs.com ".
Quando uso HtmlAgilityPack per sostituire più HtmlNode, ma alcuni si sono confusi cose ----- Non può sostituire.
Il codice è:
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;
}
}
}
}
Sono così confuso e perché?
replaceChild (), insertAfter () improvvisamente entrambi hanno smesso di funzionare anche per me.
la mia migliore alternativa era sostituire innerhtml con "new html string"
targetnode.innerhtml = newNodeAsString;
modificare:
c'era un errore in HtmlAgilityPack che inserisce valori / nodi. a causa di alcuni caching per farlo funzionare più velocemente.
ecco perché l'ho abbandonato. e usato AngleSharp .
modificare:
a metà 2017 HAP è in fase di sviluppo qui . non tornerò indietro inoltre non puoi creare problemi con HAP.