Get contents of div name by class using web browser control?

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

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

I need to get the InnerText of a div element. I tried using the following code:

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

But the above code does not work! and according to decision 1 for a similar issue on another site , it says:

The first thing that caught my attention: <div class="thin"> does not define the name of the div element, it defines the CSS style class. Instead, use the attribute name (or both), for example: <div class="thin" name="thin"> .

How can I get innerText from a div if there is only a class attribute?

Any help would be greatly appreciated

+4
source share
3 answers

You should use ClassName instead of class.

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

Link

+12
source

Add runat="server" and ID attributes

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

After adding the runat="server" attribute runat="server" you can use it to call by identifier in the code, as an object.

 string result = hello_div.InnerText; //or InnerHtml 
+1
source
  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 { } } 
0
source

All Articles