Search code examples
excelvbaauthenticationinternet-explorer

Login to web page and scraping data using VBA


I'm coding a macro that will load a web page, login in it and get the datas from a table. Thanks to several topics here I've done that:

Sub sail2()
    Dim ie As Object
    Set ie = New(InternetExplorer.Application")
    ie.Visible = True
    ie.Navigate "http://pfrwtekref/websail/"
    With ie
    Dim oLogin As Object, oPassword As Object
    Set oLogin = .document.getElementById("txtPwd")(0)
    Set oPassword = .document.getElementById("txtPwd")(0)
        oLogin.Value = test
        oPassword.Value = test
        .document.forms(0).submit
    End With
End Sub

But I have two type of errors "automation error" if I launch the macro and "error 462 - server not available"

Can anyone help me ? Thanks for reading and have a good day !


Solution

  • The first issue seems to be that you have a mismatched comma on the third line; however, seeing as you're are complaining about an automation error I think that may be just a typo on this site.

    I can't see your internal website so I'm just guessing but I suspect the next issue is that there is no element with ID "txtPwd". You can check to confirm by pressing Ctrl-Shift-C and then selecting the username and password entry boxes.

    Finally, depending on how the site is set up your .document.forms(0).submit may not work. You may need to find the ID for the submit button class submit. Below is a function I created a while back for such a task:

    Function logIn(userName As String, password As String) As Boolean
        'This routine logs into the grade book using given credentials
        
        Dim ie As New InternetExplorer
        Dim doc As HTMLDocument
        On Error GoTo loginFail
        
        ie.Navigate "[website here]"
        'ie.Visible = True
        Do While ie.ReadyState <> READYSTATE_COMPLETE Or ie.Busy: DoEvents: Loop 'Wait server to respond
        Set doc = ie.Document
        doc.getElementsByName("u_name").Item(0).Value = userName 'These may be different for you
        doc.getElementsByName("u_pass").Item(0).Value = password
        doc.getElementsByClassName("btn").Item(0).Click
        
        Do While ie.ReadyState <> READYSTATE_COMPLETE Or ie.Busy: DoEvents: Loop 'Wait server to respond
        Set doc = ie.Document
        'Add a check to confirm you aren't on the same page
        ie.Quit
        Set ie = Nothing
        LogIn = True
        Exit Function
        
    loginFail:
        MsgBox "There was an issue logging in. Please try again."
        logIntoGradeBook = False
    End Function
    

    Note that the site I was dealing with was set up poorly and so I needed to switch to GetElementsByName and GetElementsByClassName to get access to what I needed. You may be fine with IDs.