【cl】selenium实例一:打开百度,获取第四个标题

/*创建类的时候是TestNG Class*/

package Selenium_lassen;

import static org.junit.Assert.*;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Case4 {
WebDriver driver;
@Test
public void test() {

System.setProperty("webdriver.firefox.bin", "D:\ruanjian\Firefox\azml\firefox.exe");
driver=new FirefoxDriver();//打开Firefox; open firefox
driver.get("http://www.baidu.com");//打开百度open the url
driver.findElement(By.id("kw")).sendKeys("GitHub");//输入搜索关键字“GitHub";input search keyword
driver.findElement(By.id("su")).click();//点击搜索按钮click the search button
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);//等页面加载,10秒内不加载成功即报超时。waiting for 10 seconds
String aResult=driver.findElement(By.xpath(".//*[@id='4']/h3/a")).getText();//取第四条搜索结果的标题。 get the text of 4th search result
System.out.println("标题是:"+aResult);
assert aResult.contains("GitHub");//做断言 assertion

driver.findElement(By.xpath(".//*[@id='4']/h3/a")).click();//打开第四个搜索结果。Open the 4th search result on baidu
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);//等页面加载,10秒内不加载成功即报超时。waiting for 10 seconds

//获取所有窗口的handle,然后逐个切换,直到切换到最新窗口 switch to the new window
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}

String aTitle=driver.getTitle();//取新窗口的title
System.out.println("current widnow title is:"+aTitle);//打出来看看

assert aTitle.contains("GitHub");//断言

}

}

原文地址:https://www.cnblogs.com/dieyaxianju/p/5033399.html