Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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.

like image 786
Rafik Bari Avatar asked Apr 20 '13 22:04

Rafik Bari


2 Answers

You should use ClassName instead of class:

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

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

like image 168
aliassce Avatar answered Nov 02 '22 22:11

aliassce


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
like image 32
zkanoca Avatar answered Nov 03 '22 00:11

zkanoca