C# Webbrowser How can I get innerHTML from a span within a div

Asked

Viewed 268 times

2

HI GUYS.

I need to get c# the innerHTML of the first SPAN element that has a value with numbers that is inside a div and I I’ve even written a code that’s on the right track, I think. So far this is it.:

             HtmlElementCollection Elems;
              WebBrowser WebOC = webBrowser;
              Elems = WebOC.Document.GetElementsByTagName("div");

              foreach (HtmlElement elem in Elems) {

                  if ((elem.GetAttribute("id") == "MyId")) {


                  }         
              }

To do this with Javascript I can with this code below

HTML

<div id="myId" class=""><span>874.005.877-81</span><span class="clipboard-copy"></span></div>

JAVASRIPT

var x = document.getElementById("myId");
var val = x.querySelector("span").innerHTML;
alert(val);

Thank you for any solution to this ;D

1 answer

0


In a perfect scenario, just take your id, and then the first span element after the document is loaded:

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    string html = webBrowser1.Document.GetElementById("myId").GetElementsByTagName("span")[0].InnerHtml;
}

But there are other factors that can change that:

The page is not fully loaded in the Documentcompleted event (use ajax for example).

You may or may not have the element with its ID = myId. You should check for existence.

May or may not have elements span within the selected element. You should check whether it contains.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.