【问题标题】:Wait for finished download file in selenium and c#在 selenium 和 c# 中等待完成的下载文件
【发布时间】:2015-04-19 15:07:58
【问题描述】:

我有一些问题。 单击 Web 应用程序上的图标后,我下载了一个文件。 我的下一步是在下载记录文件之前执行。 我要等到文件下载完成?

有人知道如何等待吗?

【问题讨论】:

  • 你使用什么网络驱动程序?

标签: c# selenium wait


【解决方案1】:

我使用以下脚本(文件名应该传入)。

第一部分等到文件出现在磁盘上(适用于 chrome)

第二部分等到它停止变化(并开始有一些内容)

var downloadsPath = Environment.GetEnvironmentVariable("USERPROFILE") + @"\Downloads\" + fileName;
for (var i = 0; i < 30; i++)
{
    if (File.Exists(downloadsPath)) { break; }
    Thread.Sleep(1000);
}
var length = new FileInfo(downloadsPath).Length;
for (var i = 0; i < 30; i++)
{
    Thread.Sleep(1000);
    var newLength = new FileInfo(downloadsPath).Length;
    if (newLength == length && length != 0) { break; }
    length = newLength;
}

【讨论】:

    【解决方案2】:

    我从 Dmitry 的回答开始,添加了一些对控制超时和轮询间隔的支持。 这是解决方案:

    /// <exception cref="TaskCanceledException" />
    internal async Task WaitForFileToFinishChangingContentAsync(string filePath, int pollingIntervalMs, CancellationToken cancellationToken)
    {
        await WaitForFileToExistAsync(filePath, pollingIntervalMs, cancellationToken);
    
        var fileSize = new FileInfo(filePath).Length;
    
        while (true)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new TaskCanceledException();
            }
    
            await Task.Delay(pollingIntervalMs, cancellationToken);
    
            var newFileSize = new FileInfo(filePath).Length;
    
            if (newFileSize == fileSize)
            {
                break;
            }
    
            fileSize = newFileSize;
        }
    }
    
    /// <exception cref="TaskCanceledException" />
    internal async Task WaitForFileToExistAsync(string filePath, int pollingIntervalMs, CancellationToken cancellationToken)
    {
        while (true)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new TaskCanceledException();
            }
    
            if (File.Exists(filePath))
            {
                break;
            }
    
            await Task.Delay(pollingIntervalMs, cancellationToken);
        }
    }
    

    你可以这样使用它:

    using var cancellationTokenSource = new CancellationTokenSource(timeoutMs);
    WaitForFileToFinishChangingContentAsync(filePath, pollingIntervalMs, cancellationToken);
    

    指定超时后会自动触发取消操作。

    【讨论】:

      【解决方案3】:
      猜你喜欢
      • 2015-03-14
      • 2023-01-28
      • 2018-05-25
      • 2013-12-22
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多