2、selenium初探--浏览器操作
对于浏览器,我们的第一操作就是打开,然后,调整到合适的大小,然后输入网址,现在用selenium来实现它;
1、浏览器最大设置。
浏览器最大设置
2、随意设置浏览器大小,一般我们会把浏览器大小设置的和平板和pc大小进行测试。
1 import org.openqa.selenium.chrome.ChromeDriver; 2 import org.openqa.selenium.WebDriver; 3 public class setBrowser{ 4 public static void main(String[] args){ 5 //打开浏览器 6 WebDriver driver = new ChromeDriver(); 7 //将浏览器设置为移动端大小 8 driver.manager().Window().setSize(new Diemsion(600, 800)); 9 System.out.println("browser will be closed"); 10 driver.quit(); 11 System.out.println("browser is closed") 12 } 13 }
3、访问链接,selenium提供的访问链接的方法有两种,即:get();和navigate.to(),一般情况下使用get简单省事;
1 import org.openqa.selenium.Webdriver; 2 import org.openqa.selenium.chrome.ChromeDriver; 3 public class ToUrl{ 4 public static void main(String[] args)throws InterruptException{ 5 WebDriver driver = new ChromeDriver(); 6 String url1 = "http://www.baidu.com"; 7 String url2 = "http://www.sogou.com"; 8 Thread.sleep(2000); 9 System.out.println("will be open Url"); 10 driver.get(url1); 11 System.out.println(url1) 12 Thread.sleep(3000); 13 driver.navigate().to(url2); 14 System.out.println(url2); 15 Thread.sleep(3000); 16 System.out.println("browser will be closed"); 17 driver.close(); 18 } 19 }
4、浏览器前进和后退,模拟浏览器刷新:driver.navigate().forward();浏览器前进
driver.navigate().back();浏览器后退
driver.navigate().refresh();刷新浏览器
1 import org.openqa.selenium.WebDriver; 2 import org.openqa.selenium.chrome.ChromeDriver; 3 4 public class BrowserGo 5 { 6 public static void main(String[] args) 7 { 8 System.out.println("broser back and forward."); 9 WebDriver driver = new ChromeDriver(); 10 11 String firstUrl = "http://www.baidu.com"; 12 13 System.out.printf("now accesss %s \n", firstUrl); 14 15 driver.get(firstUrl); 16 String secondUrl = "http://news.baidu.com"; 17 System.out.printf("now accesss %s \n", secondUrl); 18 19 driver.get(secondUrl); 20 System.out.printf("now back to %s \n", firstUrl); 21 22 driver.navigate().back();//控制浏览器后退 23 System.out.printf("forward to %s \n", secondUrl); 24 25 driver.navigate().forward();//控制浏览器前进 26 27 driver.navigate().refresh();//模拟浏览器刷新 28 driver.quit(); 29 } 30 }