如何使用VBA和Chromedriver优化等待方法

时间:2018-11-29 17:26:18

标签: vba selenium web-scraping selenium-chromedriver wait

在此主页“ http://www.kpia.or.kr/index.php/year_sugub”中

如果您检查html,则从li1到li6有6个ID。第一次使用chromedriver后,我注意到的第一件事是wait方法无效。因此,在单击互联网以在此主页上使用后,我搜索了各种方法来优化等待时间。 例如,我应用了以下三种编码。

ex1) Application.Wait Now + TimeSerial(0,0,5)

ex2) .FindElementById(“ li2”,超时:= 10000)。点击

ex3) '做 'DoEvents '错误恢复下一个 '设置ele = .FindElementById(“ li2”) '出错时转到0 “如果计时器-t = 10,然后退出执行” <==为避免无限循环 '当ele什么都没有时循环

但是,如果不使用Application.Wait Now + TimeSerial(0,0,5),我们最终找不到一种优化等待方法的方法。单击li2后,此方法未完全加载,但偶尔会执行其他任务。

因此,我想到了一种正式的编码逻辑,以后我可能会偶尔使用它进行类似的编码,因此我想到了以下逻辑。例如,在li2中,乙烯值始终是带有结果值的固定值,因此,如果单击li2并查找“ SM”值,则数据将被加载到工作表中。接下来,li3中的“ LDPE”是在加载完成后将数据粘贴到工作表中的方法。因此,我使用这种想法进行编码,而在使用VBA时我无法解决该错误。

Dim d As WebDriver, ws As Worksheet, clipboard As Object
Set d = New ChromeDriver
Set ws = ThisWorkbook.Worksheets("Sheet3")
Set clipboard = GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
Const URL = "http://www.kpia.or.kr/index.php/year_sugub"
Dim html As HTMLDocument

Set html = New HTMLDocument

With d
    .AddArgument "--headless"
    .Start "Chrome"
    .get URL, Raise:=False
rep:
    .FindElementById("li2", timeout:=10000).Click

    Dim Posts As WebElements
    Dim elem As WebElements
    Dim a1 As Integer

    For Each Posts In .FindElementsByClass("bbs")
        For Each elem In Posts.FindElementsByCss("td")
            If Not elem.Text = "SM" Is Nothing Then

html.body.innerHTML = d.PageSource

Dim tarTable As HTMLTable
Dim hTable As HTMLTable

For Each tarTable In html.getElementsByTagName("table")
    If InStr(tarTable.className, "bbs") <> 0 Then
    Set hTable = tarTable
    End If
Next

    clipboard.SetText .FindElementById("table_body").Attribute("outerText")
    clipboard.PutInClipboard

    else
    goto rep
    end if
    .Quit

End With

如果找到与SM值匹配的值,则假定加载已完成,然后继续将相关数据传输到剪贴板。如果找不到SM值,请使用GOTO来使用.FindElementById(“ li2”超时:= 10000)。我以为可以通过创建从.Click重新启动的循环来解决此问题。

我是节省时间并在阅读时努力学习的初学者,因此,如果您能给我更多帮助,我将不胜感激。

enter image description here

1 个答案:

答案 0 :(得分:1)

我将完全避免使用浏览器,并发出XMLHTTP POST请求并解析XML响应以写出工作表。循环遍历覆盖每个标签的gubun代码,即gubun = 1到6。

Option Explicit

Public Sub GetTable()
    Dim sResponse As String, body As String, columnToWriteOut As Long, gubunNumber As Long
    Dim xmlDoc As Object

    Set xmlDoc = CreateObject("MSXML2.DOMDocument") 'New MSXML2.DOMDocument60
    columnToWriteOut = 1

    With CreateObject("MSXML2.XMLHTTP")

        For gubunNumber = 1 To 6

            body = "gubun=" & CStr(gubunNumber)
            .Open "POST", "http://www.kpia.or.kr/index.php/year_sugub/get_year_sugub", False
            .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
            .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"
            .setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"
            .setRequestHeader "Content-Length", Len(body)
            .send body
            sResponse = .responseText

            With xmlDoc
                .validateOnParse = True
                .setProperty "SelectionLanguage", "XPath"
                .async = False
                If Not .LoadXML(sResponse) Then
                    Err.Raise .parseError.ErrorCode, , .parseError.reason
                End If
            End With

            Dim startYear As Long, endYear As Long, numColumns As Long, numRows As Long, data()
            Dim node As Object, nextNode As Object, headers(), i As Long

            startYear = xmlDoc.SelectSingleNode("//rec/sy").Text
            endYear = xmlDoc.SelectSingleNode("//rec/ey").Text
            numRows = xmlDoc.SelectNodes("//product").Length

            ReDim headers(1 To endYear - startYear + 3)
            numColumns = UBound(headers)
            ReDim data(1 To numRows, 1 To numColumns)
            headers(1) = "Product": headers(2) = "Category"

            For i = 1 To endYear - startYear + 1
                headers(i + 2) = startYear + i - 1
            Next

            Dim r As Long, c As Long, rowCounter As Long

            rowCounter = 0
            For Each node In xmlDoc.SelectNodes("//rec")  ' '//rec/*[not(self::sy) and not(self::ey) and not(self::product)]  ?
                c = 1: rowCounter = rowCounter + 1
                For Each nextNode In node.ChildNodes
                    Select Case c
                    Case 3
                        data(rowCounter, 1) = nextNode.Text
                    Case Is > 3
                        data(rowCounter, c - 1) = nextNode.Text
                    End Select

                    Select Case rowCounter Mod 4
                    Case 1
                        data(rowCounter, 2) = "Production (shipment)"
                    Case 2
                        data(rowCounter, 2) = "Export"
                    Case 3
                        data(rowCounter, 2) = "income"
                    Case 0
                        data(rowCounter, 2) = "Domestic demand "
                    End Select
                    c = c + 1
                Next
            Next

            With ThisWorkbook.Worksheets("Sheet1")
                .Cells(1, columnToWriteOut).Resize(1, UBound(headers)) = headers
                .Cells(2, columnToWriteOut).Resize(UBound(data, 1), UBound(data, 2)) = data
            End With
            columnToWriteOut = columnToWriteOut + UBound(headers) + 2
        Next
    End With
End Sub

或者,您可以循环等待每个Ajax调用完成:

Option Explicit

Public Sub GetInfo()
    Dim d As WebDriver, ws As Worksheet, clipboard As Object, writeOutColumn As Long
    writeOutColumn = 1
    Const URL = "http://www.kpia.or.kr/index.php/year_sugub"

    Set d = New ChromeDriver
    Set ws = ThisWorkbook.Worksheets("Sheet3")
    Set clipboard = GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")

    With d
        .Start "Chrome"
        .get URL

        Dim links As Object, i As Long
        Set links = .FindElementsByCss("[href*=action_tab]")

        For i = 1 To links.Count
            If i > 1 Then
                links(i).Click
                Do
                Loop While Not .ExecuteScript("return jQuery.active == 0")
            End If
            Dim table As Object
            Set table = .FindElementByTag("table")
            clipboard.SetText table.Attribute("outerHTML")
            clipboard.PutInClipboard

            ws.Cells(1, writeOutColumn).PasteSpecial
            writeOutColumn = writeOutColumn + table.FindElementByTag("tr").FindElementsByTag("td").Count + 2
            Set table = Nothing
        Next
        .Quit
    End With
End Sub