0

this is the html code

<span class="vi-atw-txt">Add to watch list</span>

I use following code to click it

webBrowser1.Document.GetElementById("vi-atw-txt").InvokeMember("click"); 

but it showing a nullreferenceexception...

what should i do?

2 Answers2

0

You are passing a classname into GetElementById which will not work. C# does not offer a method to search by class name directly, but you can try the solution in How to getelement by class? except with a span as the tag to search for, and then fire the click when your class matches.

var links = webBrowser1.Document.GetElementsByTagName("span");
foreach (HtmlElement link in links)
{
    if (link.GetAttribute("className") == "vi-atw-txt")
    {
        link.InvokeMember("click");
    }
}

What this code will do is create a collection of all spans, and then search through those spans until it finds a span with a classname of "vi-atw-txt". Once that is found, it will call click on that span.

Stefan H
  • 6,635
  • 4
  • 24
  • 35
  • thanks. i need little more something to ask.. i need to click and wait 3 seconds and move to the next line of code. tell me how to do it.. – Supun Madhushanka Dec 28 '17 at 23:48
  • The most direct way would be System.Threading.Thread.Sleep(3000); – Stefan H Dec 28 '17 at 23:49
  • The code I provided will stop execution for 3 seconds before allowing it to move forward. If you need to do all of this code separately from the UI thread, then you should put all of it in a separate thread. – Stefan H Dec 28 '17 at 23:51
  • i don't know how to do it.. i am executing these on a timer1_tick https://scontent.fcmb1-1.fna.fbcdn.net/v/t1.0-9/26114143_159366131495805_607926980461952724_n.jpg?oh=e9277efc396e50fc60700a9500a05c7e&oe=5AB0DA30 – Supun Madhushanka Dec 28 '17 at 23:56
0

To use the method getElementById you would have to add an id to the span tag:

<span id="someid" class="vi-atw-txt">Add to watch list</span>

Then:

webBrowser1.Document.GetElementById("someid").InvokeMember("click"); 
SBFrancies
  • 3,987
  • 2
  • 14
  • 37
  • I'm assuming the OP does not control the page they are browsing with the webBrowser object, and can therefore not arbitrarily add Ids. – Stefan H Dec 28 '17 at 23:41
  • Good point, obviously this answer is only relevant if the user can edit the html (which they don't specify). – SBFrancies Dec 28 '17 at 23:47