使用 <a href> child 从 <div class> 获取 innerText

Get innerText from <div class> with an <a href> child

我正在使用 C# 中的 webBrowser,我需要从 link 中获取文本。 link 只是一个没有 class.

的 href

像这样

<div class="class1" title="myfirstClass">
<a href="link.php">text I want read in C#
<span class="order-level"></span>

不应该是这样吗?

        HtmlElementCollection theElementCollection = default(HtmlElementCollection);
        theElementCollection = webBrowser1.Document.GetElementsByTagName("div");
        foreach (HtmlElement curElement in theElementCollection)
        {
            if (curElement.GetAttribute("className").ToString() == "class1")
            {
                HtmlElementCollection childDivs = curElement.Children.GetElementsByName("a");
                foreach (HtmlElement childElement in childDivs)
                {
                    MessageBox.Show(childElement.InnerText);
                }

            }
        }

这里我创建了控制台应用程序来提取锚文本。

static void Main(string[] args)
        {
            string input = "<div class=\"class1\" title=\"myfirstClass\"><a href=\"link.php\">text I want read in C#<span class=\"order-level\"></span>";
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(input);
            foreach (HtmlNode item in doc.DocumentNode.Descendants("div"))
            {
                var link = item.Descendants("a").First();
                var text = link.InnerText.Trim();
                Console.Write(text);
            }
            Console.ReadKey();
        }

请注意这是 htmlagilitypack 问题,因此请正确标记问题。

这是通过标签名称获取元素的方式:

String elem = webBrowser1.Document.GetElementsByTagName("div");

然后你应该提取 href 的值:

var hrefLink = XElement.Parse(elem)
     .Descendants("a")
     .Select(x => x.Attribute("href").Value)
     .FirstOrDefault();

如果你有超过 1 个 "a" 标签,你也可以放入一个 foreach 循环,如果这是你想要的。

编辑:

使用 XElement:

调用element.ToString()即可获取包含外节点的内容。

如果要排除外层标签,可以调用String.Concat(element.Nodes()).

使用 HtmlAgilityPack 获取 innerHTML:

  1. NuGet 安装 HtmlAgilityPack。
  2. 使用此代码。

HtmlWeb web = new HtmlWeb();

HtmlDocument dc = web.Load("Your_Url");

var s = dc.DocumentNode.SelectSingleNode("//a[@name="a"]").InnerHtml;

希望对您有所帮助!