从网页中选择复选框和输入框以下载数据

时间:2018-10-12 15:07:12

标签: excel vba selenium web-scraping

我正在使用Excel VBA导航到http://airyards.com/tables.html

  • 我只想选中“ WR”,“ TE”和“ RB”复选框。

  • 然后将输入框(即“添加或删除星期”框)设置为一个星期,我可以在代码的前面的变量中进行设置。例如i = 5,然后在该框中输入i,这样我只能从第5周开始获取数据。

  • 最后,我要单击“下载数据”按钮,然后将数据保存到特定的名称和文件夹;最好在其中包含我的变量“ i”的内容来标识星期和我选择的文件夹。

由于我对Selenium VBA有点熟悉,所以一直在使用它。但是我无法选择复选框,无法在“添加或删除星期”输入框中输入所需的星期数。

我的代码:

Dim driver As Selenium.ChromeDriver
Set driver = New Selenium.ChromeDriver
Const URL = "http://airyards.com/tables.html"

With driver
    .Start "chrome", "https://www.google.com/"
    .Get URL
    .FindElementByXPath("//*[@id='position']/div/div[2]/label/input").Click 'try to click the "TE" check box, but does not work
End With

1 个答案:

答案 0 :(得分:0)

您需要切换到包含的iframe,然后在单击之前首先检查是否已选择。我包括单击下载按钮的方法,提取下载URL的方法。我使用提取的URL二进制下载文件。我使用sendKeys delete来选择星期。

Option Explicit
Public Sub MakeSelectionsDownloadFile()
    Dim d As WebDriver, t As Date, downloadURL As String, s As String
    Const MAX_WAIT_SEC As Long = 5
    Const URL = "http://airyards.com/tables.html"
    Const keepWeek As Long = 5

    Set d = New ChromeDriver

    With d
        .Start "Chrome"
        .Get URL
        .SwitchToFrame 0

        With .FindElementByCss("[value=WR]")
            If Not .IsSelected Then .Click
        End With
        With .FindElementByCss("[value=TE]")
            If Not .IsSelected Then .Click
        End With
        With .FindElementByCss("[value=RB]")
            If Not .IsSelected Then .Click
        End With
        With .FindElementByCss("[value=UNK]")
            If .IsSelected Then .Click
        End With

        Dim i As Long, keys As New Selenium.keys
        For i = 1 To 6
            If i <> keepWeek Then
                .FindElementByCss("[data-value='" & i & "']").ClickAndHold
                .SendKeys keys.Delete
            End If
        Next

        t = Timer

        Do
            DoEvents
            downloadURL = .FindElementById("download").Attribute("href")
            If Timer - t > MAX_WAIT_SEC Then Exit Do
        Loop While downloadURL = vbNullString
        '  .FindElementById("download").Click

        s = DownloadFile("C:\Users\User\Desktop\", downloadURL)
        .Quit
    End With
End Sub

Public Function DownloadFile(ByVal downloadFolder As String, ByVal downloadURL As String) As String
    Dim http As Object, tempArr As Variant
    Set http = CreateObject("MSXML2.XMLHTTP")
    http.Open "GET", downloadURL, False
    http.send

    On Error GoTo errhand

    With CreateObject("ADODB.Stream")
        .Open
        .Type = 1
        .write http.responseBody
        .SaveToFile downloadFolder & "Test.csv", 2
        .Close
    End With
    DownloadFile = downloadFolder & "Test.csv"
    Exit Function
errhand:
    If Err.Number <> 0 Then
        Debug.Print Err.Number, Err.Description
        MsgBox "Download failed"
    End If
    DownloadFile = vbNullString
End Function