首页 > 解决方案 > 使用 vba 自动使用 Internet Explorer 11 下载文件

问题描述

我正在尝试使用 InternetExplorer.Application 下载文件,但它总是打开一个窗口,要求保存或打开文件。有没有办法绕过这个并让它在后台运行和保存?这是我尝试过的一段代码。

Set ie = CreateObject("InternetExplorer.Application")
ie.Navigate "https://pastebin.com/raw/terAweb"
State = 0
Do Until State = 4
DoEvents
State = ie.readyState
Loop
Dim file: file= ie.Document.Body.innerHTML

标签: vbaautomationinternet-explorer-11

解决方案


请参考下面的示例代码,使用getElementbyId方法找到下载按钮后,会显示下载提示,我们可以使用Application.SendKeys "%{s}"命令点击保存按钮。

Sub downloadfile()

        Dim IE As Object, Data As Object
        Dim ticket As String

        Set IE = CreateObject("InternetExplorer.Application")

        With IE
            .Visible = True
            .navigate ("https://dillion132.github.io/default.html")

            While IE.ReadyState <> 4
                DoEvents
            Wend

            'Trigger the download button to download the file
            IE.Document.getElementbyId("btnDowloadReport").Click

            'wait the download prompt appear
            Application.Wait (Now + TimeValue("00:00:03"))

            '
            Application.SendKeys "%{s}"

        'Waiting for the site to load.
        'loadingSite
        End With
        Set IE = Nothing
    End Sub

网页内容:

<a id="btnDowloadReport" href="https://research.google.com/pubs/archive/44678.pdf" download>Download</a>

推荐阅读