【问题标题】:How to wait for file download to complete before closing Chrome?如何在关闭 Chrome 之前等待文件下载完成?
【发布时间】:2020-05-26 05:07:27
【问题描述】:

我正在使用 Selenium VBA 和 Chrome 下载 csv 文件。

在一些速度较慢的 PC 上,浏览器会在下载完成之前关闭。

我使用过bot.Timeouts.PageLoad = 500000bot.Timeouts.Server = 500000(我之前将'bot'声明为New ChromeDriver)。这适用于我需要 Chrome 等到点击链接、找到元素等,但在执行 bot.Quit

时似乎没有任何影响

使用任意的bot.Wait (5000) 有效,但在某些 PC 上不需要等待这么长时间,有时需要等待更长时间。

有什么方法可以让 Chrome 等到下载完成后再运行bot.Quit

【问题讨论】:

  • Here 是 Java 和 Python selenium 中提供的解决方案,以确保脚本等待文件下载完成。您可以在 vba 中实现该解决方案,如果您需要任何帮助,请告诉我。
  • 你是说这行代码吗? downloadPercentage = driver.execute_script("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress').value")
  • 是的,该行将获得下载的百分比,您必须迭代直到它达到 100% 或达到最大超时。
  • 好的,那么我如何迭代直到达到 100%?
  • 让我把sn-p给我。

标签: vba selenium google-chrome selenium-chromedriver


【解决方案1】:

这是sn-p到while循环。

Function getDownLoadedFileName(maxTimeInMins As int)
    Dim startTime As Date
    startTime = Now()
    Dim downloadPercentage As int
    Do While ElapsedTime(Now(),startTime) < maxTimeInMins 
         downloadPercentage = driver.execute_script( "return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress').value")
        If (downloadPercentage = 100) Then
            getDownLoadedFileName = driver.execute_script("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content  #file-link').text")
        End If
    Loop
End Function

Function ElapsedTime(endTime As Date, startTime As Date) 
    Dim Interval As Date 
    ' Calculate the time interval. 
    Interval = endTime - startTime 

    ' Format and return the time interval in seconds. 
    ElapsedTime = Int(CSng(Interval * 24 * 3600))
End Function

【讨论】:

  • 由于我的机器配置,我没有机会执行代码。请测试逻辑,让我知道它是怎么回事。
  • 好的...你是说把它粘贴到我的 VBA 代码中然后...?
  • 你可以通过点击元素模仿下载后调用该函数。此功能将确保在关闭浏览器/您的下一行代码之前完成下载。
猜你喜欢
  • 1970-01-01
  • 2015-09-22
  • 2011-04-14
  • 2021-11-22
  • 1970-01-01
  • 2020-09-14
  • 2015-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多