Selenium调用Robot上传图片

之前我一直是调用AotuIT上传图片,

但是我感觉那个太麻烦了,

还要另外安装AotuIT,

现在使用JDK自带的Robot类。

打开百度首页:

Selenium调用Robot上传图片_第1张图片

点击相机图标:

Selenium调用Robot上传图片_第2张图片

再点击本地上传图片:

Selenium调用Robot上传图片_第3张图片


import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

public class Baidu_1 {
    @BeforeMethod
    public void beforeMethod() throws InterruptedException {
        Read.openBaidu();
        //打开百度首页
    }

    @Test
    public void login() throws InterruptedException, AWTException {
        Read.driver.findElement
                (By.xpath(".//*[@id='form']/span[1]/span")).click();
        //点击相机图标
        Thread.sleep(1000);
        WebElement element = Read.driver.findElement
                (By.xpath(".//*[@id='form']/div/div[2]/div[2]/input"));
        ((JavascriptExecutor) Read.driver).executeScript
                ("arguments[0].click();", element);
        //模拟JS点击本地上传图片
        Thread.sleep(1000);

        String path = System.getProperty("user.dir") + 
                "\\src\\main\\resources\\timg.jpg";
        StringSelection stringSelection = new StringSelection(path);
        //指定图片的路径,使用相对路径
        Toolkit.getDefaultToolkit().getSystemClipboard()
                .setContents(stringSelection, null);
        //把图片路径复制粘贴到剪切板

        Robot robot = new Robot();
        robot.keyPress(KeyEvent.VK_ENTER);
        //按下Enter键
        robot.keyRelease(KeyEvent.VK_ENTER);
        //释放Enter键

        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        //按下Ctrl+V
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_V);
        //释放Ctrl+V

        robot.keyPress(KeyEvent.VK_ENTER);
        //再次点击Enter键
        robot.keyRelease(KeyEvent.VK_ENTER);
        //再次释放Enter键

        Thread.sleep(5000);
    }

    @AfterMethod
    public void afterMethod() {
        Read.quit();
    }
}


你可能感兴趣的:(Selenium(Java))