0 背景
- 开发工具idea
- 代码管理maven
- jdk1.8
- webdriver chrome
1 chromedriver & chrome
chromedriver和chrome要对应上:
- chomedriver下载地址:淘宝镜像 这里用的是 chromedriver88-0-4324-96.zip
- chrome下载地址:如何降级和安装旧版本的Chrome? 这里用的是 ChromeStandaloneSetup_88.0.4324.150.exe
2 jar包 & 代码
pom.xml
View Code
code
import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import java.time.Duration; import java.util.Iterator; import java.util.Set;public class SearchBaidu {public static void main(String[] args) throws InterruptedException {String chromedriver_win="D:\\Code\\seleniumDemo\\src\\main\\resources\\chromedriver.exe";System.setProperty("webdriver.chrome.driver", chromedriver_win);WebDriver webDriver= new ChromeDriver();MutiWindowTest(webDriver);Thread.sleep(2000);webDriver.get("https://www.baidu.com");webDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));Dimension d =new Dimension(800,600);webDriver.manage().window().setSize(d);Thread.sleep(2000);Point p=new Point(500,300);webDriver.manage().window().setPosition(p);Thread.sleep(2000);webDriver.manage().window().fullscreen();Thread.sleep(3000);webDriver.manage().window().maximize();WebElement searchInput=webDriver.findElement(By.id("kw"));//定位到文本,将文本高亮显示//创建一个JavascriptExecutor对象JavascriptExecutor js =(JavascriptExecutor)webDriver;//新闻文本高亮显示颜色js.executeScript ( "arguments[0].setAttribute('style', arguments[1]);",searchInput,"background: orange; border: 2px solid red;");Thread.sleep (5000);searchInput.sendKeys("selenium1 selenium2 区别"); // WebElement searchBtn=webDriver.findElement(By.id("su"));WebElement searchBtn = webDriver.findElement(By.cssSelector("input[value=百度一下]"));searchBtn.click();Thread.sleep(2000);webDriver.quit();}private static void MutiWindowTest(WebDriver driver)throws InterruptedException {WebDriver newWindow = null ;driver.get("http://www.hao123.com/");//浏览器最大化driver.manage().window().maximize();//获取当前页面句柄String current_handles = driver.getWindowHandle();//点击 百度链接driver.findElement(By.xpath("//*[@data-title='百度' and contains(@class,'sitelink')]")).click();//接下来会有新的窗口打开,获取所有窗口句柄Set<String> all_handles = driver.getWindowHandles();//循环判断,把当前句柄从所有句柄中移除,剩下的就是你想要的新窗口Iterator<String> it = all_handles.iterator();while(it.hasNext()){if(current_handles == it.next()) continue;//跳入新窗口,并获得新窗口的driver - newWindownewWindow = driver.switchTo().window(it.next());}//接下来在新页面进行操作,也就是百度首页,我们输入一个java关键字进行搜索Thread.sleep(1000);WebElement baidu_keyowrd = newWindow.findElement(By.id("kw"));baidu_keyowrd.sendKeys("java");WebElement searchBtn=newWindow.findElement(By.id("su"));searchBtn.click();Thread.sleep(3000);//关闭当前窗口,主要使用close而不是quite,newWindow.close();Thread.sleep(1000);driver.switchTo().window(current_handles);System.out.println(driver.getCurrentUrl());} }