C# 使用 Web 浏览器控件按类名获取 div 的内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16126068/
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-10 00:05:18  来源:igfitidea点击:

Get the content of a div by class name using Web Browser control?

c#.net

提问by Rafik Bari

I have a form with webBrowser1control that is used to load a page that contains in its HTML part the following line:

我有一个带有webBrowser1控件的表单,用于加载一个页面,该页面的 HTML 部分包含以下行:

 ...
 <div class="cls">
 Hello World !
 </div>

I need to get the innerTextof the divelement. I tried the following:

我需要得到innerText的的div元素。我尝试了以下方法:

 string result = "";
 foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div"))
                if (el.GetAttribute("class") == "cls")
                {
                    result = el.InnerText;
                }

But the code above doesn't seem to work, and according to Solution 1 for a similar question on another website, it is stated that

但是上面的代码似乎不起作用,根据另一个网站上类似问题的解决方案1,它指出

First thing which caught my eye is: <div class="thin">does not define the name of the divelement, it defines its CSS style class. Instead, use the attribute name (or both), for example: <div class="thin" name="thin">.

首先引起我注意的是:<div class="thin">没有定义div元素的名称,它定义了它的 CSS 样式类。相反,使用属性名称(或两者),例如:<div class="thin" name="thin">

How can I get the innerTextof the divelement, if there is a classattribute only?

我怎样才能获得innerText的的div元素,如果有一个class属性而已?

Any help would be highly appreciated.

任何帮助将不胜感激。

采纳答案by aliassce

You should use ClassNameinstead of class:

您应该使用ClassName代替class

 if (el.GetAttribute("className") == "cls") { … }

For details, see HtmlElement.GetAttribute("class") doesn't run.

有关详细信息,请参阅HtmlElement.GetAttribute("class") 不运行

回答by zkanoca

Add runat="server"and IDattributes to the divas follows:

添加runat="server"ID属性div如下:

 …
 <div class="cls" ID="hello_div" runat="server">
 Hello World !
 </div>

After adding runat="server"attribute, you can use it calling by IDon the code behind like an object:

添加runat="server"属性后,您可以ID像对象一样在后面的代码上调用它:

string result = hello_div.InnerText; // or InnerHtml

回答by user5152667

        HtmlDocument doc = webBrowser1.Document;
        HtmlElementCollection divs = doc.GetElementsByTagName("div");

        foreach (HtmlElement div in divs)
        {
            try
            {
                var info = div.DomElement;
                PropertyInfo[] pi = info.GetType().GetProperties();

                string strClass = pi[0].GetValue(div.DomElement).ToString();

                if (strClass == "cls")
                {
                        //DoStuff
                }
            }
            catch
            {

            }
        }