首页 > 解决方案 > 检查用户是否已经登录,如果是则跳过

问题描述

我正在创建网页抓取代码以登录网站并输入一些数据。在进入实际页面之前有登录表单。我的代码首先登录。但是,如果您已经登录,网站不会要求登录。有没有办法检查是否需要登录?

这是我的代码:

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

标签: excelvbaweb-scraping

解决方案


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

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

推荐阅读