以最簡單的例子來說明,我們需要在bing搜索引擎中,輸入並查詢“Selenium自動化測試”幾個字。可以很快就寫出如下代碼:
String queryString = "Selenium自動化測試"; WebElement element = driver.findElement(By .xpath("//input[@id='sb_form_q']")); // 直接輸入查詢字符串 element.sendKeys(queryString); // 點擊查詢按鈕 driver.findElement(By.xpath("//input[@id='sb_form_go']")).click(); // 截圖函數 captureScreenshot("截圖測試JUnit");
但是如果我們想把當前的粘貼板Clipboard中的數據粘貼到bing的搜索輸入框,該怎么辦呢?Selnium是否支持從從粘貼板中粘貼數據呢?答案是肯定的,直接上代碼,代碼很簡單,並且有注釋,不再進行解釋。
import java.awt.*; import java.awt.datatransfer.StringSelection; import java.awt.event.KeyEvent; import java.io.*; import java.util.concurrent.TimeUnit; import org.junit.*; import org.openqa.selenium.*; import org.openqa.selenium.chrome.*; import com.thoughtworks.selenium.SeleneseTestBase; public class SearchChineseCharacters extends SeleneseTestBase { private static WebDriver driver; static final int MAX_TIMEOUT_IN_SECONDS = 5; @BeforeClass public static void setUpBeforeClass() throws Exception { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + File.separator + "chromedriver.exe"); driver = new ChromeDriver(); String url = "http://cn.bing.com/"; driver.manage().window().maximize(); driver.manage().timeouts() .implicitlyWait(MAX_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); driver.get(url); } @AfterClass public static void tearDownAfterClass() throws Exception { if (driver != null) { System.out.println("運行結束!"); driver.quit(); } } @Test public void test() { String queryString = "Selenium自動化測試"; WebElement element = driver.findElement(By .xpath("//input[@id='sb_form_q']")); // 直接輸入查詢字符串 // element.sendKeys(queryString); // 下面的語句模擬復制粘貼功能、copy & paste // 向粘貼板中存放數據,還可以注釋掉下面的語句,進行手工復制一些東西到粘貼板 setClipboardData(queryString); // 模擬Ctrl+V,進行粘貼 Robot robot = null; try { robot = new Robot(); } catch (AWTException e1) { e1.printStackTrace(); } robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_V); robot.keyRelease(KeyEvent.VK_V); robot.keyRelease(KeyEvent.VK_CONTROL); // 點擊查詢按鈕 driver.findElement(By.xpath("//input[@id='sb_form_go']")).click(); // 截圖函數 captureScreenshot("截圖測試JUnit"); } private void captureScreenshot(String fileName) { String imagePath = System.getProperty("user.dir") + File.separator + fileName + ".png"; try { byte[] decodedScreenshot = ((TakesScreenshot) driver) .getScreenshotAs(OutputType.BYTES); FileOutputStream fos = new FileOutputStream(new File(imagePath)); fos.write(decodedScreenshot); fos.close(); System.out.println("截圖保存至" + imagePath); } catch (Exception e) { e.printStackTrace(); } } public static void setClipboardData(String string) { StringSelection stringSelection = new StringSelection(string); Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(stringSelection, null); } }
使用場景:
1.上傳文件,
2.富文本框都行