如何通过excel VBA在IE11中浏览PDF时单击下载botton

时间:2018-09-27 10:06:25

标签: excel-vba automation ie-automation

子Drop_Down() 昏暗objIE作为对象,ele作为对象,opt作为对象 设置objIE = CreateObject(“ InternetExplorer.Application”)

objIE.Visible = True
objIE.navigate "https://isgs-oas.isgs.illinois.edu/reports/rwservlet?oil_permit_activity"

Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop

Set ele = objIE.document.getElementsByTagName("INPUT")

For Each opt In ele
    If opt.getAttribute("name") = "p_YEAR" Then
        opt.Focus
        opt.Value = "2018"
        Exit For
    End If
Next opt

Set ele = objIE.document.getElementsByTagName("select")

For Each opt In ele
    If opt.getAttribute("name") = "p_MONTH" Then
        opt.Focus
        opt.Value = "January"
        Exit For
    End If
Next opt
objIE.document.forms(0).submit
Do While objIE.Busy: DoEvents: Loop

'请在此处帮助 “想立即下载PDF文件

结束子

2 个答案:

答案 0 :(得分:1)

我通过遍历月份和年份并将其转换为字符串来构造URL,然后将其连接到URL的基础。我猜想您要从哪一年开始,您会在“ For year =“声明中看到。

List of PDFs

Sub DownloadFile()
Dim WinHttpReq As Object
Dim oStream As Object
Dim myURL As String
Dim LocalFilePath As String
Dim month As String
Dim year As Integer
Dim monthNo As Integer

For year = 2010 To 2018
    For monthNo = 1 To 12
        month = MonthName(monthNo)
            myURL = "https://isgs-oas.isgs.illinois.edu/reports/rwservlet?hidden_run_parameters=oil_permit_activity&p_MONTH=" & month & "&p_YEAR=" & CStr(year)
            LocalFilePath = Environ("USERPROFILE") & "\Desktop\rwservlet\oil_permit_activity_" & month & "_" & CStr(year) & ".pdf"

                Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
                WinHttpReq.Open "GET", myURL, False, "", ""  '("username", "password")
                WinHttpReq.send

                If WinHttpReq.Status = 200 Then
                    Set oStream = CreateObject("ADODB.Stream")
                    oStream.Open
                    oStream.Type = 1
                    oStream.Write WinHttpReq.responseBody
                    oStream.SaveToFile LocalFilePath, 2 ' 1 = no overwrite, 2 = overwrite
                    oStream.Close
                End If
    Next monthNo
Next year
End Sub

上面的代码对我有用,但是您必须确保桌面上存在文件夹“ rwservlet”,否则它将引发错误(我不擅长错误处理,但是我们都在学习中)。否则,您可以更改LocalFilePath字符串。

答案 1 :(得分:0)

如果您已经知道查询参数的名称,则可以自动构建URL。我使用Chrome的检查器找到了上面示例的网址(“ https://isgs-oas.isgs.illinois.edu/reports/rwservlet?hidden_run_parameters=oil_permit_activity&p_MONTH=January&p_YEAR=2018”)。

您可以对脚本进行重新整理以根据参数自动构建URL,然后使用其中的多个“从URL保存文件”脚本之一。这是我在SE上找到的一个: Downloading a file in VBA and storing it

希望它会有所帮助:)