描述:selenium webdriver学习--打开新窗口,并判断新窗口是否与目标窗口一致,若一致则切换到该窗口并获取标题
跳出if判断,获取父级标题,并关闭
HTML标签不太明显时,可以用路径表示:
driver.findElement(By.xpath("/html/body/div/div[4]/div[6]/p[2]/a"));
import java.util.Set; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Wait; import org.openqa.selenium.support.ui.WebDriverWait; public class YsfTest_20180725{ public static void main(String[] args) throws InterruptedException{ WebElement search = null; System.setProperty("webdriver.chrome.driver","C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://www.w3school.com.cn/html/html_forms.asp"); //获得父级窗口的id String parentId = driver.getWindowHandle(); //获取父级窗口的标题名 String parentTitle = driver.getTitle(); //找到“亲自试一试”按钮 search = driver.findElement(By.xpath("/html/body/div/div[4]/div[6]/p[2]/a")); //点击“亲自试一试”按钮 search.click(); //获取父级窗口id和子级窗口id,放在chirldids数组里 Set<String> childids = driver.getWindowHandles(); // System.out.println("list:"+chirldids); for(String s:childids){ if(driver.switchTo().window(s).getTitle().contains("W3School在线测试工具 V2")){ driver.switchTo().window(s); String titleChild = driver.getTitle(); System.out.println("name:"+titleChild); Thread.sleep(5000); driver.close(); break; } } driver.switchTo().window(parentId); String titleParent = driver.getTitle(); System.out.println("name:"+titleParent); driver.close(); } }
重点实现了切换窗口的功能。