How to download an image using Selenium (any version)?

前端 未结 13 1553
夕颜
夕颜 2020-11-29 04:11

I was wondering, how can one use selenium/webdriver to download an image for a page. Assuming that the user session is required to download the image hence having pure URL i

13条回答
  •  遥遥无期
    2020-11-29 04:50

    For my use case there were cookies and other issues that made the other approaches here unsuitable.

    I ended up using an XMLHttpRequest to populate a FileReader (from How to convert image into base64 string using javascript, and then calling that using Selenium's ExecuteAsyncScript (as shown in Selenium and asynchronous JavaScript calls). This allowed me to get a Data URL which was straight forward to parse.

    Here's my C# code for getting the Data URL:

    public string ImageUrlToDataUrl(IWebDriver driver, string imageUrl)
    {
      var js = new StringBuilder();
      js.AppendLine("var done = arguments[0];"); // The callback from ExecuteAsyncScript
      js.AppendLine(@"
        function toDataURL(url, callback) {
          var xhr = new XMLHttpRequest();
          xhr.onload = function() {
            var reader = new FileReader();
            reader.onloadend = function() {
              callback(reader.result);
            }
            reader.readAsDataURL(xhr.response);
          };
          xhr.open('GET', url);
          xhr.responseType = 'blob';
          xhr.send();
        }"); // XMLHttpRequest -> FileReader -> DataURL conversion
      js.AppendLine("toDataURL('" + imageUrl + "', done);"); // Invoke the function
    
      var executor = (IJavaScriptExecutor) driver;
      var dataUrl = executor.ExecuteAsyncScript(js.ToString()) as string;
      return dataUrl;
    }
    

提交回复
热议问题