使用 Selenium WebDriver 和 Java Robot 类上传文件。


我们可以在 Selenium webdriver 中使用 Java Robot 类上传文件。它可以产生键盘和鼠标事件的仿真。它衍生自AWT 包

语法

Robot r = new Robot();
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);

示例

代码实现

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import java.awt.*;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.openqa.selenium.JavascriptExecutor;
public class RobotUplFile{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
      driver.get("http://my.monsterindia.com/create_account.html");
      // scroll to reach upload button
      JavascriptExecutor j = (JavascriptExecutor)driver;
      j.executeScript("scroll(0,500)");
      // file path passed as parameter to StringSelection
      StringSelection s = new StringSelection("C:\Users\ghs6kor\Pictures\test.txt");
      // Clipboard copy
      Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s,null);
      //identify element and click
      driver.findElement(By.xpath("//*[text()='Choose file']")).click();
      // Robot object creation
      Robot r = new Robot();
      //pressing enter
      r.keyPress(KeyEvent.VK_ENTER);
      //releasing enter
      r.keyRelease(KeyEvent.VK_ENTER);
      //pressing ctrl+v
      r.keyPress(KeyEvent.VK_CONTROL);
      r.keyPress(KeyEvent.VK_V);
      //releasing ctrl+v
      r.keyRelease(KeyEvent.VK_CONTROL);
      r.keyRelease(KeyEvent.VK_V);
      //pressing enter
      r.keyPress(KeyEvent.VK_ENTER);
      //releasing enter
      r.keyRelease(KeyEvent.VK_ENTER);
   }
}

输出

更新于: 28-Dec-2020

7K+ 浏览

开启您的事业

完成课程获得认证

开始
广告