简体   繁体   中英

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

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

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

I need to get the innerText of the div element. I tried the following:

 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

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

How can I get the innerText of the div element, if there is a class attribute only?

Any help would be highly appreciated.

You should use ClassName instead of class :

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

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

Add runat="server" and ID attributes to the div as follows:

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

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

string result = hello_div.InnerText; // or InnerHtml
        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
            {

            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM