VB WebBrowser click button

2019-08-23 07:10发布

问题:

On this web page: https://www.youtube.com/upload_defaults
I would like to call a function and then click the "Save" button in the upper right corner.

There is no ID or Name. How can I do this?

回答1:

You can use the distinct CSS class of the button: account-save-button

In VB.NET, use HtmlDocument.GetElementsByTagName like this:

Private Sub ClickSaveButton()
    If (WebBrowser1.Document IsNot Nothing) Then 
        Dim Elems As HtmlElementCollection 
        Dim WebOC as WebBrowser = WebBrowser1

    Elems = WebOC.Document.GetElementsByTagName("BUTTON")

        For Each elem As HtmlElement In Elems
            Dim CssClass As String = elem.GetAttribute("classname")

            If ((CssClass IsNot Nothing) And (CssClass.Length <> 0)) Then 
                If CssClass.ToLower().Contains("account-save-button") Then 
                    elem.InvokeMember("click");
                    Exit For
                End If 
            End If 
        Next 
    End If 
End Sub

To verify it with just a web browser, try this from your browser's developer console; it works because youtube uses jQuery:

$(".account-save-button").click();

Or pure javascript: document.getElementsByClassName('account-save-button')[0].click();

For reference, here is the button's markup:

<button class="yt-uix-button yt-uix-button-size-default yt-uix-button-primary account-save-button account-action-button" type="submit" onclick=";return true;"><span class="yt-uix-button-content">Save</span></button>

Other thoughts:

  • This is basically screen scraping, which can lead to brittle applications when the page changes, etc.
  • Google may already have a web service API for what you are trying to accomplish.. but that's a good question: What exactly are you trying to accomplish? What is the context? We may be able to suggest a better alternate solution.

Update:

I checked the Youtube API Reference, but I don't see anything for setting preferences for upload defaults.