使用VBA单击IE中的按钮

时间:2018-05-22 09:11:13

标签: vba internet-explorer

我正在尝试从网页自动下载,并且需要我按一个按钮才能访问登录表单。

我已经搜索了网络和各种线程的答案,运气不错,但现在我收到了错误:

  

'对象不支持此属性或方法'。

我要点击的按钮的HTML部分是:

<button name="idpEndpointId" type="submit" value="https://saml.nemlog-in.dk"   class="btn btn-primary">Vælg</button>

有什么建议吗?

Private Sub download()

Dim IE As Object
Dim document As Object
Dim nemKnap As Object

'Create IE object
Set IE = CreateObject("InternetExplorer.Application")

'Show browser
IE.Visible = True

'Navigate to URL
IE.Navigate "https://link.com/"

'Statusbar if waittime
Application.StatusBar = "Page is loading."

'Wait
'Application.Wait Now + TimeValue("00:00:02")

' First attempt on tabbing through the website to press enter
  '  SendKeys "{TAB}"
  '  SendKeys "{TAB}"
  '  SendKeys "{TAB}"
  '  SendKeys "{TAB}"
  '  SendKeys "{TAB}"
  '  SendKeys "{TAB}"
  '  SendKeys "{TAB}"

'Do
'Loop While IE.busy

Do
Loop Until IE.readystate = 3
Do
Loop Until IE.readystate = 4

Set nemKnap = IE.document.getElementsByValue("https://saml.nemlog-in.dk")

'nemKnap.Click // is supposed to happen afterwards

End Sub

2 个答案:

答案 0 :(得分:1)

或者使用CSS queryselector

Option Explicit

Public Sub ClickButton()

    Dim IE As New InternetExplorer, html As HTMLDocument

    With IE
        .Visible = True
        .navigate "https://kommune.bbr.dk/IdPSelection#!/"
        While .Busy = True Or .readyState < 4: DoEvents: Wend
        Set html = .document
    End With

   html.querySelector("button.btn.btn-primary[value=""https://saml.nemlog-in.dk""]").Click

   Stop   '<== delete this line later. This is just to enable you to observe result.
   '<Other code>
   .Quit

End Sub

答案 1 :(得分:0)

您提供的链接包含您提到的按钮,但值不同。

<button name="idpEndpointId" type="submit" value="https://saml.adgangsstyring.stoettesystemerne.dk" class="btn btn-primary">Vælg</button>

有几种方法可以点击此按钮。我根据您的具体情况看到的最简单方法是单击第3个按钮。该网站有3个按钮,您可以执行以下操作:

IE.document.getElementsByTagName("button")(2).Click

按钮数组从0开始,这就是为什么2是第3个按钮的原因。

另一种方法是循环所有按钮并找到你想要的按钮:

Set allButtons = IE.document.getElementsByTagName("button")
Do While i < allButtons.Length
    If allButtons(i).Type = "submit" And allButtons(i).Value = "https://saml.adgangsstyring.stoettesystemerne.dk" Then
        allButtons(i).Click
        Exit Do
    End If
    i = i + 1
Loop