C# 使用 HtmlAgilityPack 解析 HTML 页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1512562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:18:36  来源:igfitidea点击:

Parsing HTML page with HtmlAgilityPack

c#htmlhtml-agility-pack

提问by Hassen

Using C# I would like to know how to get the Textbox value (i.e: john) from this sample html script :

使用 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>

采纳答案by gpmcadam

There are a number of ways to select elements using the agility pack.

有多种使用敏捷包选择元素的方法。

Let's assume we have defined our HtmlDocumentas follows:

假设我们已经定义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. Simple LINQ
We could use the Descendants()method, passing the name of an element we are in search of:

1. 简单的 LINQ
我们可以使用该Descendants()方法,传递我们要搜索的元素的名称:

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:

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
Or we could use XPath.

3. XPath
或者我们可以使用XPath

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

Console.WriteLine(name);
//John

回答by TrueWill

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);
}

I wrote this pretty quickly, so you'll want to do some testing with more data.

我写得很快,所以你需要用更多的数据做一些测试。

NOTE: The XPath strings apparently have to be in lower-case.

注意:XPath 字符串显然必须是小写的。

EDIT: Apparently the beta now supports Linq to Objects directly, so there's probably no need for the converter.

编辑:显然测试版现在直接支持 Linq to Objects,因此可能不需要转换器。