1、操作浏览器窗口
package cn.china; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.openqa.selenium.Dimension; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterMethod; public class ApiTest2 { public WebDriver driver; String baseUrl; @Test public void browserWindow() { baseUrl="http://www.sogou.com"; driver.navigate().to(baseUrl); driver.manage().window().setPosition(new Point(50, 50)); driver.manage().window().setSize(new Dimension(500, 500)); System.out.println(driver.manage().window().getPosition()); System.out.println(driver.manage().window().getSize()); driver.manage().window().maximize(); } @BeforeMethod public void beforeMethod() { System.setProperty("webdriver.chrome.driver", "C:\\chromedriver\\chromedriver.exe"); driver =new ChromeDriver(); } @AfterMethod public void afterMethod() { try{ Thread.sleep(3000); }catch(InterruptedException e){ e.printStackTrace(); } driver.quit(); } }
2、获取页面源码资源
public void pageSource() { baseUrl="http://www.sogou.com"; driver.navigate().to(baseUrl); String title=driver.getTitle(); Assert.assertEquals("搜狗搜索引擎 - 上网从搜狗开始", title); System.out.println(title); String page=driver.getPageSource(); Assert.assertTrue(page.contains("购物")); System.out.println(page); String Url=driver.getCurrentUrl(); Assert.assertEquals("https://www.sogou.com/", Url); System.out.println(Url);
3、页面刷新、模拟单击浏览器的前进、后退功能
@Test public void page() { baseUrl="http://www.sogou.com"; driver.navigate().to(baseUrl); driver.navigate().to("http://www.dangdang.com"); driver.navigate().back(); driver.navigate().forward(); driver.navigate().refresh();
4、针对输入框的部分操作
@Test public void page() { baseUrl="http://www.sogou.com"; driver.navigate().to(baseUrl); WebElement input=driver.findElement(By.id("query")); input.clear(); input.sendKeys("测试工程师指定输入内容"); driver.findElement(By.id("stb")).click();
5、模拟键盘、鼠标操作page
@Test public void page() { baseUrl="http://www.sogou.com"; driver.navigate().to(baseUrl); WebElement input=driver.findElement(By.id("query")); input.sendKeys("selenium webdriver API"); Actions action = new Actions(driver); action.contextClick(input).perform();//鼠标右击 action.doubleClick(input).perform();//鼠标双击 input.sendKeys(Keys.chord(Keys.CONTROL+"a"));//使用sendkeys方法模拟键盘组合操作 input.sendKeys(Keys.chord(Keys.CONTROL+"c")); WebElement inputBox=driver.findElement(By.id("inputBox")); inputBox.sendKeys(Keys.chord(Keys.CONTROL+"v")); action.keyDown(Keys.CONTROL);//使用Actions对象模拟键盘操作 action.keyUp(Keys.CONTROL); action.keyDown(Keys.SHIFT).sendKeys("abcdef").perform(); //鼠标悬浮 WebElement link1=driver.findElement(By.xpath("//a[@id=‘link1‘]")); action.moveToElement(link1).perform();
时间: 2024-12-29 11:18:45