在 Selenium 4 中,您可以使用 executeScript() 方法执行 JavaScript 来操作文件上传。以下是一个示例代码:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class FileUploadExample {
    public static void main(String[] args) {
        // 设置 ChromeDriver 路径
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        // 创建 ChromeOptions 对象,用于设置浏览器选项
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--disable-infobars"); // 禁用信息栏

        // 创建 ChromeDriver 对象,并传入 ChromeOptions
        WebDriver driver = new ChromeDriver(options);

        // 导航到文件上传页面
        driver.get("http://example.com/file-upload-page");

        // 执行 JavaScript 代码来设置文件路径
        String filePath = "path/to/file";
        ((JavascriptExecutor) driver).executeScript("document.getElementById('fileInput').value = arguments[0];", filePath);

        // 其他操作...

        // 关闭浏览器
        driver.quit();
    }
}

在上述示例中,我们首先设置了 ChromeDriver 的路径,然后创建了一个 ChromeOptions 对象,并禁用了信息栏。接下来,我们创建了 ChromeDriver 对象,并传入 ChromeOptions。然后,我们使用 get() 方法导航到文件上传页面。

在执行 JavaScript 代码时,我们使用 executeScript() 方法,并传入 JavaScript 代码。在这个例子中,我们使用 document.getElementById('fileInput').value = arguments[0]; 来设置文件路径。fileInput 是文件上传输入框的 ID,arguments[0] 是 JavaScript 代码中的参数,表示文件路径。

最后,您可以执行其他操作,然后关闭浏览器。

请注意,上述示例中的文件路径应该是正确的本地文件路径。

Selenium 4 文件上传:使用 executeScript() 方法操作 JavaScript

原文地址: https://www.cveoy.top/t/topic/SEq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录