需要一些HTML元素与htmllagilitypack在c# -如何做到这一点

本文关键字:何做 这一点 htmllagilitypack HTML 元素 | 更新日期: 2023-09-27 18:09:36

我有以下场景:

<a href="test.com">Some text <b>is bolded</b> some is <b>not</b></a>

现在,我如何得到"test.com"部分和文本的锚,没有加粗的部分?

需要一些HTML元素与htmllagilitypack在c# -如何做到这一点

假设以下标记:

<html>
<head>
    <title>Test</title>
</head>
<body>
    <a href="test.com">Some text <b>is bolded</b> some is <b>not</b></a>
</body>
</html>

您可以执行以下操作:

class Program
{
    static void Main()
    {
        var doc = new HtmlDocument();
        doc.Load("test.html");
        var anchor = doc.DocumentNode.SelectSingleNode("//a");
        Console.WriteLine(anchor.Attributes["href"].Value);
        Console.WriteLine(anchor.InnerText);
    }
}

打印:

test.com
Some text is bolded some is not

当然,你可能需要调整SelectSingleNode XPath选择器,为你想要获取的锚提供一个唯一的id或类名:

// assuming <a href="test.com" id="foo">Some text <b>is bolded</b> some is <b>not</b></a>
var anchor = doc.GetElementbyId("foo");
相关文章: