J'implémente une fonctionnalité pour demander la page " http://cnblogs.com ".
Lorsque j'utilise HtmlAgilityPack pour remplacer plus de HtmlNode, mais que certains événements se produisent, il est difficile de remplacer ----
Le code est:
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;
}
}
}
}
Je suis tellement confus et pourquoi?
replaceChild (), insertAfter () a soudainement cessé de fonctionner pour moi aussi.
ma meilleure alternative a été de remplacer innerhtml par "new html string"
targetnode.innerhtml = newNodeAsString;
modifier:
HtmlAgilityPack avait un bogue en insérant des valeurs / nœuds. en raison de la mise en cache pour le rendre plus rapide.
c'est pourquoi je l'ai laissé tomber. et utilisé AngleSharp .
modifier:
à la mi-2017, HAP est en cours de développement ici . je n'y retournerai pas. De plus, vous ne pouvez pas créer de problème chez HAP.