使用精确的HTML搜索或将HTMLElement转换为HTMLNode获取HtmlAgilityPack Node

本文关键字:转换 HTMLElement HTMLNode 获取 Node HtmlAgilityPack 搜索 HTML | 更新日期: 2023-09-27 18:36:17

我使用默认的.net WebBrowser创建了一个HTMLElement选择器(DOM)。 用户可以通过单击来选择(选择)一个 HTMLElement。

我想获取与 HTMLElement 对应的 HtmlAgilityPack.HTMLNode。

最简单的方法(在我看来)是使用文档。DocumentNode.SelectSingleNode(EXACTHTMLTEXT),但它并没有真正起作用(因为该函数只接受xpath代码)。

我该怎么做?

用户选择的示例 HTMLElement 如下所示(The OuterHtml Code):

<a onmousedown="return wow" class="l" href="http://site.com"><em>Great!!!</em> <b>come and see more</b></a>

当然,可以选择任何元素,这就是为什么我需要一种方法来获取 HTMLNode。

使用精确的HTML搜索或将HTMLElement转换为HTMLNode获取HtmlAgilityPack Node

相同的概念,但更简单一些,因为您不必知道元素类型:

HtmlNode n = doc.DocumentNode.Descendants().Where(n => n.OuterHtml.Equals(text, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
我想

出了一个解决方案。不知道这是否是最好的(如果有人知道实现此目的的更好方法让我知道,我将不胜感激)。

以下是将获得 HTMLNode 的类:

public HtmlNode GetNode(string text)
        {
            if (text.StartsWith("<")) //get the type of the element (a, p, div etc..)
            {
                string type = "";
                for (int i = 1; i < text.Length; i++)
                {
                    if (text[i] == ' ')
                    {
                        type = text.Substring(1, i - 1);
                        break;
                    }
                }
                try //check to see if there are any nodes of your HTMLElement type that have an OuterHtml equal to the HtmlElement Outer HTML. If a node exist, than that's the node we want to use
                {
                    HtmlNode n = doc.DocumentNode.SelectNodes("//" + type).Where(x => x.OuterHtml == text).First();
                    return n;
                }
                catch (Exception)
                {
                    throw new Exception("Cannot find the HTML element in the HTML Page");
                }
            }
            else
            {
                throw new Exception("Invalid HTML Element supplied. The selected HTML element must start with <");
            }
        }

这个想法是你传递HtmlElement的OuterHtml。例:

HtmlElement el=....
HtmlNode N = GetNode(el.OuterHtml);