How can I click a js button on VB

2020-02-16 01:14发布

i am using visual basic 12.there is a web browser in my form.İ want to click it but i have a problem.The button is a javascript button.so this code doesn't work:

WebBrowser1.Document.All("button id").InvokeMember("click")

Here is the hmtl of button.How can i click it.

<a class="single_like_button btn3-wrap" onclick="openFbLWin_407311();">
                                        <span>&nbsp;</span><div class="btn3">Like</div></a>

1条回答
啃猪蹄的小仙女
2楼-- · 2020-02-16 02:14

Three options:

  1. Execute the javascript function itself directly
  2. Search through all A elements using InnerHTML
  3. Search through all A elements using ClassName

Execute the javascript function itself directly

Edit: Thanks to pquest for pointing out you can execute the javascript function directly with:

Browser.InvokeScript("openFbLWin_407311");

More complicated (and not really necessary) :

WbBrowser.Navigate( new Uri("javascript:(function(){ openFbLWin_407311(); })();") )

Search through all A elements using InnerHTML

Have a look at the following question: Click an HTML link inside a WebBrowser Control

In your case, based on that link, something like this:

Dim links As HtmlElementCollection
links = WebBrowser1.Document.GetElementsByTagName("A")

For Each link As HtmlElement In links
   If link.InnerHtml.IndexOf("Like") <> -1 Then
            link.InvokeMember("Click")
   End If
Next

Search through all A elements using ClassName

 If link.GetAttribute("className") = "single_like_button btn3-wrap" Then
    link.InvokeMember("Click")
 End If

All Three Methods:

VB.net

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        WebBrowser1.Url = New Uri("file:///D:/clickJSbutton.html")
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Method 1: Execute javascript directly
         Browser.InvokeScript("openFbLWin_407311");
         'WebBrowser1.Navigate(New Uri("javascript:(function(){ openFbLWin_407311(); })();"))

        'Method 2: Find the link from all links
        Dim links As HtmlElementCollection
        links = WebBrowser1.Document.GetElementsByTagName("A")

        For Each link As HtmlElement In links
            'Method 2B: Using some kind of inner html
            If link.InnerHtml.IndexOf("Like") <> -1 Then
                link.InvokeMember("Click")
            End If

            'Method 2C: Using className as identifier
            If link.GetAttribute("className") = "single_like_button btn3-wrap" Then
                link.InvokeMember("Click")
            End If

        Next

    End Sub
End Class
查看更多
登录 后发表回答