Lesic
Lesic

Reputation: 136

Can't get element of web browser document

I'm doing some webscraping from a WinForms-Application. Here's a snippet from the browser document I want to scrape from:

<div class="div1" id="id1" data-on-choice="asdf">
<h4>Target:</h4>                                                            
<table class="table1" style="width: 100%;">
    <tbody><tr>
        <td>
            <div class="div2">
                <label>aa</label>
                <label>ab</label>
                <label>ac</label>
            </div>                                                                  
            <div class="div3" id="id2">
                <span class="span1" role="status" aria-live="polite"></span>
            </div>
            <a class="anchor1" style="display: inline;" href="#"></a>                       
        </td>
    </tr>
    <tr>
        <td>
            <div class="div4">
                <span></span>
                <span></span>
                <span></span>
            </div>
        </td>
    </tr>
</tbody></table>

The HtmlElement I want to get and click on would be the anchor "anchor1". Note that I have done similar stuff numerous times, but I just can't seem to get this particular element. Even when I print the InnerHtml of all anchor-elements of my document, there is not a line for this element.

Html-Agility-Pack is not an option, as my application is too big to recode. The html is not under my control, so assigning id's to elements, ... is not an option either.

In my opinion this should do the trick, it is not working though:

HtmlElement elementToClick = browser.Document.GetElementsByTagName("a")
         .Cast<HtmlElement>()
         .FirstOrDefault(m => m.GetAttribute("class") == "anchor1");
elementToClick.InvokeMember("click");

Upvotes: 1

Views: 2180

Answers (2)

sam
sam

Reputation: 969

You can invoke click on your required a tag by invoking the javascript like this:

browser.InvokeScript("document.querySelector('a.anchor1').click()");

Your invoked script will run on the web document loaded on the your web browser control.

For more info on InvokeScript, refer to WebBrowser.InvokeScript Method

Upvotes: 0

Volkan Paksoy
Volkan Paksoy

Reputation: 6937

Since class is a special name it doesn't return the value for that. You should use className instead. Snippet below worked for me:

var elementToClick = browser.Document
            .GetElementsByTagName("a")
            .Cast<HtmlElement>()
            .FirstOrDefault(m => m.GetAttribute("className") == "anchor1");

Upvotes: 3

Related Questions