c# - 使用 HtmlAgilityPack 解析 HTML 页面

标签 c# html html-agility-pack

使用 C# 我想知道如何从此示例 html 脚本中获取文本框值(即:john):

<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 如下:

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。简单的 LINQ
我们可以使用 Descendants()方法,传递我们正在搜索的元素的名称:

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

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

<强>2。更高级的 LINQ
我们可以使用更高级的 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
或者我们可以使用 XPath .

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

Console.WriteLine(name);
//John

关于c# - 使用 HtmlAgilityPack 解析 HTML 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1512562/

相关文章:

c# - HtmlAgilityPack 读取 html 时出现问题

c# - jquery改变后如何获取HtmlDocument? (HtmlAgilityPack)

c# - 高效算法计算点之间的距离

html - ODB 错误 80040e14 ASP 经典

Javascript不使用parseInt函数添加两个字符串数字

jquery - 如何创建在您选择基本文本时复制的悬停文本?

c# - 使用 HTML Agility 搜索所需数据后,如何从网页中抓取数据

c# - 如何分割一个字节[]

c# - 在 XAML 中设置元素内容时,WPF 如何确定要设置的属性?

c# - 从列表中删除具有最低 Num 属性的重复对象