Java selenium fills out Vue/React forms by directly setting the value attribute of the form element

Vue form

The following is a valuesample code that fills out a Vue form and submits it by directly setting the property of the form element.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FillVueForm {
    
    

    public static void main(String[] args) {
    
    
        // 设置 Chrome 浏览器驱动路径
        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");

        // 创建 Chrome 浏览器实例
        WebDriver driver = new ChromeDriver();

        // 打开 Vue 表单页面
        driver.get("http://example.com/vue/form");

        // 直接设置表单元素的 value 属性
        WebElement nameInput = driver.findElement(By.name("name"));
        nameInput.sendKeys("");
        nameInput.clear(); // 清空输入框内容,确保下面的设置生效
        nameInput.sendKeys("John Doe");
        ((JavascriptExecutor) driver).executeScript("arguments[0].value = 'John Doe'; arguments[0].dispatchEvent(new Event('input'))", nameInput);

        WebElement emailInput = driver.findElement(By.name("email"));
        emailInput.sendKeys("");
        emailInput.clear(); // 清空输入框内容,确保下面的设置生效
        emailInput.sendKeys("[email protected]");
        ((JavascriptExecutor) driver).executeScript("arguments[0].value = '[email protected]'; arguments[0].dispatchEvent(new Event('input'))", emailInput);

        WebElement submitButton = driver.findElement(By.cssSelector("button[type='submit']"));

        // 提交表单
        submitButton.click();

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

This code will fill in the and fields by directly setting valuethe attribute of the form element , and then click the submit button. It should be noted that after setting the attribute, you need to manually trigger the corresponding event (such as the event) to ensure that the form data is submitted correctly.nameemailvalueinput

Again, using this method may be risky, because different browsers may have different implementation mechanisms for events, and this approach will also bypass the browser's built-in event mechanism, increasing the complexity and difficulty of the code. At the same time There may also be some potential risks. Therefore, it is recommended to still use the API provided by Selenium to fill out the form.

React form

Recat method one

If you want to valuefill out a React form by directly setting the attribute of the form element, you can refer to the sample code below.

Suppose there is a form component named in the React application LoginForm, which contains elements such as username and password. Here is an example code that uses Selenium to directly set form element valueattributes to fill out and submit a form:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.JavascriptExecutor;

public class FillReactForm {
    
    

    public static void main(String[] args) {
    
    
        // 设置 Chrome 浏览器驱动路径
        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");

        // 创建 Chrome 浏览器实例
        WebDriver driver = new ChromeDriver();

        // 打开 React 表单页面
        driver.get("http://example.com/react/form");

        // 直接设置表单元素的 value 属性
        WebElement usernameInput = driver.findElement(By.id("login-form-username"));
        usernameInput.sendKeys("");
        usernameInput.clear();
        usernameInput.sendKeys("john.doe");
        ((JavascriptExecutor) driver).executeScript("arguments[0].value = 'john.doe'; arguments[0].dispatchEvent(new Event('input'))", usernameInput);

        WebElement passwordInput = driver.findElement(By.id("login-form-password"));
        passwordInput.sendKeys("");
        passwordInput.clear();
        passwordInput.sendKeys("password123");
        ((JavascriptExecutor) driver).executeScript("arguments[0].value = 'password123'; arguments[0].dispatchEvent(new Event('input'))", passwordInput);

        WebElement loginButton = driver.findElement(By.xpath("//button[text()='Login']"));

        // 提交表单
        loginButton.click();

        // 等待表单提交完成,页面跳转到下一个页面
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.urlContains("/dashboard"));

        // 判断是否登录成功
        String pageTitle = driver.getTitle();
        if (pageTitle.equals("Dashboard")) {
    
    
            System.out.println("Login succeeded.");
        } else {
    
    
            System.out.println("Failed to login.");
        }

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

Recat method two

It should be noted that filling in React forms in this way is also risky, because different browsers may have different implementation mechanisms for events, and this approach will also bypass the browser's built-in event mechanism, increasing the complexity of the code Sex and difficulty, but there may also be some potential risks. Therefore, it is recommended to still use the API provided by Selenium to fill out the form.

If filling out React forms using directly setting the form element's valueattribute doesn't work, try using React's ReactDOMlibrary to simulate user input. The specific method is: first find the root node of the form component, then obtain the corresponding DOM element according to namethe property and method of the form element, and finally call or (as the case may be) simulate user input.ReactDOM.findDOMNode()ReactDOM.Simulate.change()ReactDOM.Simulate.input()

Here's an ReactDOMexample code that uses the library to fill out and submit a React form:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.JavascriptExecutor;

public class FillReactForm {
    
    

    public static void main(String[] args) {
    
    
        // 设置 Chrome 浏览器驱动路径
        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");

        // 创建 Chrome 浏览器实例
        WebDriver driver = new ChromeDriver();

        // 打开 React 表单页面
        driver.get("http://example.com/react/form");

        // 找到表单组件的根节点
        WebElement formRoot = driver.findElement(By.id("login-form-root"));

        // 根据表单元素的 name 属性获取对应的 DOM 元素,并模拟用户输入
        WebElement usernameInput = (WebElement) ((JavascriptExecutor) driver).executeScript("return ReactDOM.findDOMNode(arguments[0]).querySelector('[name=\"username\"]')", formRoot);
        usernameInput.sendKeys("john.doe");
        ((JavascriptExecutor) driver).executeScript("return ReactDOM.findDOMNode(arguments[0]).querySelector('[name=\"username\"]').dispatchEvent(new Event('change', {bubbles: true}))", formRoot);

        WebElement passwordInput = (WebElement) ((JavascriptExecutor) driver).executeScript("return ReactDOM.findDOMNode(arguments[0]).querySelector('[name=\"password\"]')", formRoot);
        passwordInput.sendKeys("password123");
        ((JavascriptExecutor) driver).executeScript("return ReactDOM.findDOMNode(arguments[0]).querySelector('[name=\"password\"]').dispatchEvent(new Event('change', {bubbles: true}))", formRoot);

        WebElement loginButton = driver.findElement(By.xpath("//button[text()='Login']"));

        // 提交表单
        loginButton.click();

        // 等待表单提交完成,页面跳转到下一个页面
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.urlContains("/dashboard"));

        // 判断是否登录成功
        String pageTitle = driver.getTitle();
        if (pageTitle.equals("Dashboard")) {
    
    
            System.out.println("Login succeeded.");
        } else {
    
    
            System.out.println("Failed to login.");
        }

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

It should be noted that due to React's asynchronous mechanism and componentized development method, this method still has some potential risks. If you encounter related problems, you can try to consult the official React documentation or seek help from the online community.

Guess you like

Origin blog.csdn.net/WSYLH/article/details/130127858