2009-10-03 5 views
27

utilisant C# Je voudrais savoir comment obtenir la valeur Textbox (ie: john) à partir de ce script HTML exemple:Page Parsing HTML avec HtmlAgilityPack

<TD class=texte width="50%"> 
<DIV align=right>Name :<B> </B></DIV></TD> 
<TD width="50%"><INPUT class=box value=John maxLength=16 size=16 name=user_name> </TD> 
<TR vAlign=center> 

Répondre

45

Il existe plusieurs façons de sélectionner des éléments à l'aide du pack d'agilité.

Supposons que nous avons défini notre HtmlDocument comme suit:

string html = @"<TD class=texte width=""50%""> 
<DIV align=right>Name :<B> </B></DIV></TD> 
<TD width=""50%""> 
    <INPUT class=box value=John maxLength=16 size=16 name=user_name> 
</TD> 
<TR vAlign=center>"; 

HtmlDocument htmlDoc = new HtmlDocument(); 
htmlDoc.LoadHtml(html); 

1. Simple LINQ
Nous pourrions utiliser la méthode Descendants(), en passant le nom d'un élément que nous sommes à la recherche de:

var inputs = htmlDoc.DocumentNode.Descendants("input"); 

foreach (var input in inputs) 
{ 
    Console.WriteLine(input.Attributes["value"].Value); 
    // John 
} 

2. Plus LINQ avancée
Nous pourrions réduire que par l'utilisation colombophile LINQ:

var inputs = from input in htmlDoc.DocumentNode.Descendants("input") 
      where input.Attributes["class"].Value == "box" 
      select input; 

foreach (var input in inputs) 
{ 
    Console.WriteLine(input.Attributes["value"].Value); 
    // John 
} 

3. XPath
Ou nous pourrions utiliser XPath.

string name = htmlDoc.DocumentNode 
    .SelectSingleNode("//td/input") 
    .Attributes["value"].Value; 

Console.WriteLine(name); 
//John 
+0

LINQ: Dans le cas où l'attribut n'a pas été là, je l'utilise LINQ suivant pour 'où input.Attributes [ "class"] = null && input.Attributes [ "class"] Valeur =="!. boîte "' –

2
HtmlDocument doc = new HtmlDocument(); 
doc.LoadHtml(html); 
XPathNavigator docNav = doc.CreateNavigator(); 

XPathNavigator node = docNav.SelectSingleNode("//td/input/@value"); 

if (node != null) 
{ 
    Console.WriteLine("result: " + node.Value); 
} 

J'ai écrit ce assez rapidement, de sorte que vous Je veux faire quelques tests avec plus de données.

REMARQUE: Les chaînes XPath doivent apparemment être en minuscules.

EDIT: Apparemment, la version bêta supporte désormais Linq to Objects, donc il n'y a probablement pas besoin du convertisseur.