检查用户是否已经登录,如果是则跳过

时间:2019-05-27 15:21:34

标签: excel vba web-scraping

我正在创建网络抓取代码以登录网站并输入一些数据。进入实际页面之前,需要先登录。我的代码有效,首先登录。但是,如果您已经登录,网站不会询问您是否登录。有什么方法可以检查是否需要登录?

这是我的代码:

Sub ChechAutomate()
    Dim ie As New InternetExplorer, url As String, ws As Worksheet

    Set ws = ThisWorkbook.Sheets("Other Data")

    url = "https://infra.com/"

    With ie
        .Visible = True
        .Navigate2 url

        While .Busy Or .ReadyState < 4: DoEvents: Wend

        With .Document
            .querySelector("[name=userName]").Value = "username"
            .querySelector("[name=password]").Value = "password123"
            .querySelector("[type=submit]").Click

            'While .Busy Or .ReadyState < 4: DoEvents: Wend

            .querySelector("[id=companySearchKeyData]").Value = ws.Range("T24").Value
            .querySelector("[type=submit]").Click
        End With

    End With

End Sub

2 个答案:

答案 0 :(得分:2)

您可以创建条件语句来检查您所在的页面。在这种情况下,以下逻辑可能会有所帮助:

Sub ChechAutomate()
    Dim IE As New InternetExplorer, url As String, ws As Worksheet
    Dim Html As HTMLDocument, idCheck As Object

    Set ws = ThisWorkbook.Sheets("Other Data")

    url = "https://infra.com/"

    With IE
        .Visible = True
        .Navigate2 url
        While .Busy Or .readyState < 4: DoEvents: Wend
        Set Html = .document
    End With

    Set idCheck = Html.querySelector("#login-bis-id-btn")
    If Not idCheck Is Nothing Then
        Html.querySelector("[name=userName]").Value = "username"
        Html.querySelector("[name=password]").Value = "password123"
        Html.querySelector("[type=submit]").Click
        While IE.Busy Or IE.readyState < 4: DoEvents: Wend
    Else:
        Debug.Print "You are already logged-in"
    End If

    'I don't know the role of the following two lines, though

    Html.querySelector("[id=companySearchKeyData]").Value = ws.Range("T24").Value
    Html.querySelector("[type=submit]").Click
End Sub

答案 1 :(得分:1)

最简单的检查是使用local-bin-path返回一个nodeList并检查其长度IMO。在querySelectorAll内...

With .document