尝试使用selenium和java从url获取blob图像

问题描述 投票:0回答:1

我正在尝试从网页下载图像 blob。 Blob url 如下所示:blob:https://example.com/43bdcaf9-7d30-4b80-9306-7e411533b960

如果我使用如下所示的 JavaScript(在 Chrome 浏览器中并将代码作为浏览器扩展运行),则可以下载图像并将其转换为 Base64 文本:

async function blobToBase64(blobUrl) {
    console.log(blobUrl);
    const response = await fetch(blobUrl);
    const blob = await response.blob();
    const arrayBuffer = await blob.arrayBuffer();
    const base64String = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));
    return base64String;
}

我需要使用 Selenium Chrome 驱动程序在 Java 中完成同样的事情,但无法实现。我试过下面的代码:

                    String blob = "";
                    if (driver instanceof JavascriptExecutor) {
                        blob = ((JavascriptExecutor) driver).executeScript("const response = await fetch('" + baseUrl
                                + "');" + "const blob = await response.blob();"
                                + "const arrayBuffer = await blob.arrayBuffer();"
                                + "const base64String = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));"
                                + "return base64String;").toString();

                        System.out.println(blob);
                    }

但我无法获取 url 错误。 请帮助获取图像 blob 并转换为 base64 字符串

org.openqa.selenium.JavascriptException: javascript error: Failed to fetch
  (Session info: chrome=130.0.6723.91)
Build info: version: '4.18.1', revision: 'b1d3319b48'
System info: os.name: 'Windows 11', os.arch: 'amd64', os.version: '10.0', java.version: '23'
Driver info: org.openqa.selenium.remote.RemoteWebDriver

提前致谢。

javascript java selenium-webdriver
1个回答
0
投票

不要使用JavaScriptExecutor

public static String blobToBase64(InputStream blobInputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int bytesRead;

        while ((bytesRead = blobInputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
        }
        
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return Base64.getEncoder().encodeToString(byteArray);
    }

这个输入流你可以从http url获取

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.getInputStream();// this is what you will need to invoke above method
© www.soinside.com 2019 - 2024. All rights reserved.