解析HTML页面HtmlAgilityPack [英] Parsing HTML page with HtmlAgilityPack
本文介绍了解析HTML页面HtmlAgilityPack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用C#我想知道如何获得文本框的值:从这个样品的HTML脚本(即约翰):
< TD类= texte WIDTH =50%>
< DIV ALIGN =右GT;名称:< B> < / B>< / DIV>< / TD>
< TD WIDTH =50%><输入类=框的值=约翰最大长度= 16大小= 16名= USER_NAME> < / TD>
< TR = VALIGN中心>
解决方案
有多种方法来选择使用敏捷包元素。
让我们假设我们已经定义了的HTMLDocument
如下:
字符串的html = @< TD类= texte WIDTH =50%,>
< DIV ALIGN =右GT;名称:< B> < / B>< / DIV>< / TD>
&所述; TD宽度=50%,>
< INPUT CLASS =框的值=约翰最大长度= 16大小= 16名= USER_NAME>
< / TD>
< TR = VALIGN中心>中;的HTMLDocument HTMLDOC =新的HTMLDocument();
htmlDoc.LoadHtml(HTML);
1。简单的LINQ
我们可以使用后裔()
方法,传递一个元素的名称,我们在寻找的:
VAR输入= htmlDoc.DocumentNode.Descendants(输入);的foreach(在输入VAR输入)
{
Console.WriteLine(input.Attributes [值]值);
// 约翰
}
2。更先进的LINQ
我们可以缩小下来使用LINQ票友:
VAR输入从输入=在htmlDoc.DocumentNode.Descendants(输入)
其中,input.Attributes [下课。值==盒子
选择输入;的foreach(在输入VAR输入)
{
Console.WriteLine(input.Attributes [值]值);
\t// 约翰
}
3。 XPath的
或者,我们可以使用的XPath 。
字符串名称= htmlDoc.DocumentNode
.SelectSingleNode(// TD /输入)
。.Attributes [值]值;Console.WriteLine(名);
//约翰
Using C# I would like to know how to get the Textbox value (i.e: john) from this sample html script :
<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>
解决方案
There are a number of ways to select elements using the agility pack.
Let's assume we have defined our HtmlDocument
as follows:
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
We could use the Descendants()
method, passing the name of an element we are in search of:
var inputs = htmlDoc.DocumentNode.Descendants("input");
foreach (var input in inputs)
{
Console.WriteLine(input.Attributes["value"].Value);
// John
}
2. More advanced LINQ
We could narrow that down by using fancier 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
Or we could use XPath.
string name = htmlDoc.DocumentNode
.SelectSingleNode("//td/input")
.Attributes["value"].Value;
Console.WriteLine(name);
//John
这篇关于解析HTML页面HtmlAgilityPack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文