How in vba to click a link on a web page

2019-03-01 22:16发布

问题:

I am trying to automate the login on a website. So far I managed to let the script type in a user-name and password and also click on a login button. This works just fine and I am logged into the website. Next step would be to click on some links to get to the right page where I can enter the search data the site needs to find the data for me.

This is the HTML-code of the tag involved:

<a title="Klik hier voor de dienst Kadaster-on-line" class="serviceAvailable" href="https://kadaster-on-line.kadaster.nl/default.asp" target="_self" ng-if="!menuItem.items" ng-repeat-start="menuItem in menuItems">Kadaster-on-line</a>

I have been trying to get VBA to click on a link but can't get in right. This is my latest attempt:

Set alle_keuzes = IE.document.getElementsByTagName("a")

For Each keuze_voor_kadaster In alle_keuzes        
    If keuze_voor_kadaster.getAttribute("title") = "Klik hier voor de dienst Kadaster-on-line" Then
        keuze_voor_kadaster.Click
        Exit For
    End If
Next keuze_voor_kadaster

What would be a proper way to do this?

回答1:

The link should be selectable by

ie.document.querySelector("a[title='Klik hier voor de dienst Kadaster-on-line']").click

You could also try:

ie.document.querySelector("a[title='Klik hier voor de dienst Kadaster-on-line']").FireEvent "onclick"

If you are getting an object not set/found error then:

1) Inspect the html to see ifparent frame/iframe tag which you element is found inside of.

In that case you may need syntax similar to:

ie.document.document.getElementsByTagName("frame")(frameIndexGoesHere).contentDocument.querySelector("a[title='Klik hier voor de dienst Kadaster-on-line']")

Use getElementById if the frame/iframe has an id.

2) Check you are waiting long enough for the element to be present before clicking. If that is the case ensure you have the following for page load and a loop to wait for element to be present:

After navigating to URL

While ie.Busy Or ie.readyState < 4: DoEvents: Wend

Const MAX_WAIT_SEC As Long = 5
Dim ele As Object, t As Date
t = Timer
Do
    DoEvents
    On Error Resume Next
    Set ele = ie.document.querySelector("a[title='Klik hier voor de dienst Kadaster-on-line']")
    On Error GoTo 0
    If Timer - t > MAX_WAIT_SEC Then Exit Do
Loop While ele Is Nothing

If Not ele Is Nothing Then ele.Click