51Testing软件测试论坛
标题:
Selenium上传图片
[打印本页]
作者:
yjlch1016
时间:
2018-1-24 16:05
标题:
Selenium上传图片
Selenium上传图片
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
public class BaiduUploadImg {
@Test
public void baiduUploadImg()
throws InterruptedException, AWTException {
System.setProperty("webdriver.firefox.marionette",
"src/main/resourcec/geckodriver.exe");
String baiduHomePage;
baiduHomePage = "https://www.baidu.com/";
WebDriver driver;
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(baiduHomePage);
Thread.sleep(2000);
Assert.assertEquals(driver.getTitle(),
"百度一下,你就知道");
driver.findElement
(By.xpath(".//*[@id='form']/span[1]/span")).click();
//点击相机图标
Thread.sleep(2000);
WebElement element = driver.findElement
(By.xpath(".//*[@id='form']/div/div[2]/div[2]/input"));
((JavascriptExecutor) driver).executeScript
("arguments[0].click();", element);
//模拟JS点击本地上传图片
Thread.sleep(2000);
String path = System.getProperty("user.dir")+
"\\src\\main\\resources\\img.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(3000);
Assert.assertEquals(driver.getTitle(),
"百度识图——以图搜信息,发现更多可能");
driver.close();
driver.quit();
}
}
欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/)
Powered by Discuz! X3.2