使用Excel VBA从网页下载文件

时间:2018-12-01 19:33:51

标签: html excel vba web-scraping

我正在尝试使用VBA从网站下载雨量计数据。

我找到了由用户输入定义的雨量计站号。搜索完成后,我的代码选择了与雨量计站相对应的复选框,并且数据格式不起作用。

当我手动执行此操作时,搜索完成后,我必须单击“ Dados Convencionais”以显示搜索结果。我找不到在代码中执行此操作的方法。

public static string LookupSubProfile (SubscriberProfileQuery subscriber)
{
    try
    {
        var connString = "Server = Server\\SQLEXPRESS; initial catalog = Stuff; integrated security = True;";

        var query = "SELECT * FROM Subscriber WHERE SubscriberKey = @SubscriberKey";

        using (SqlConnection conn = new SqlConnection(connString))
        {
            conn.Open();
            using (SqlCommand command = new SqlCommand(query, conn))
            {
                // 2: add parameters
                command.Parameters.Add("SubscriberKey", SqlDataType.VarChar).Value = suscriber.SuscriberKey;

                // 1. use ExecuteScalar/ExecuteReader,
                // you will need to define what exactly you need here
                var result = command.ExecuteScalar();

                if (result != null)
                {
                    // 4. return the result
                    return (string)result;
                }
            }

             // 3. remove unneeded calls
        }

        // 4. return null if nothing was found
        return null; 
    }
    catch
    {
        // 4: throw the error, log if possible
        throw;
    }
}

1 个答案:

答案 0 :(得分:2)

我已尝试保持接近您的原始代码。这些步骤包括缺少使下拉菜单显示的步骤,因此您可以选择格式等。

Option Explicit

Sub DownloadCSV()

    Dim SearchString As String
    Dim SearchBox As Object
    Dim SearchButton As Object
    Dim SelectionStationButton As Object
    Dim SelectionCSVButton As Object
    Dim DownloadButton As Object
    Dim ie As New InternetExplorer

    'User inputs station number
    SearchString = "02044054"                    'InputBox("Input rain gauge station number", "Download data HidroWeb", "Station number- e.g. 02044054")

    With ie
        .Visible = True
        .Navigate2 "http://www.snirh.gov.br/hidroweb/publico/medicoes_historicas_abas.jsf"

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

        'Station number to be searched
        Set SearchBox = .document.getElementById("form:fsListaEstacoes:codigoEstacao")
        SearchBox.Value = SearchString

        'Search button click
        Set SearchButton = .document.getElementById("form:fsListaEstacoes:bt")
        SearchButton.Click

        'click dropdown
        .document.querySelector("[href*=dadosConvencionais]").Click

        'select checkbox beside the station number
        .document.querySelector(".checkbox.i-checks i").Click

        'Select data format -  Arquivo Excel(.CSV)
        .document.querySelector("input[value='3']").Click

        'click download button
        .document.querySelector("[id='form:fsListaEstacoes:fsListaEstacoesC:btBaixar']").Click

        Application.Wait Now + TimeSerial(0, 0, 10)
        .Quit
    End With

End Sub