码迷,mamicode.com
首页 > Web开发 > 详细

Selenium上传图片

时间:2018-01-20 20:35:27      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:main   sse   ctrl+v   exce   相对路径   open   ase   com   win   

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();
}
}

Selenium上传图片

标签:main   sse   ctrl+v   exce   相对路径   open   ase   com   win   

原文地址:https://www.cnblogs.com/yjlch1016/p/8321754.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!