某些被测试的页面包含Ajax的局部刷新机制,并且会产生显示多条数据的浮动框,需要单击选择浮动框中包含某个关键字的选项。
被测试的网页:http://www.sogou.com
实例代码:
package cn.om.webdriverapi;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
public class TestAjaxDivOption {
WebDriver driver;
String url;
@Test
public void testAjaxDivOption() {
driver.get(url);
WebElement input=driver.findElement(By.id("query"));
//点击搜索框,使得浮动框显示出来
input.click();
//把浮动框里的所有选项都存在suggetionOptions里
List<WebElement> suggetionOptions=driver.findElements(By.xpath("//div[@id='vl']/div/ul/li"));
//for循环,查找想要的对象
for(WebElement element:suggetionOptions){
//把每一项的内容与目标内容进行比较,查找到想要的那个element,点击
System.out.println(element.getText());
if(element.getText().contains("无人机")){//这里比较的内容根据实际悬浮的内容来填写
System.out.println(element.getText());
element.click();
break;
}
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@BeforeMethod
public void beforeMethod() {
url = "http://www.sogou.com";
System.setProperty("webdriver.firefox.bin", "E:/Mozilla Firefox/firefox.exe");
driver = new FirefoxDriver();
}
@AfterMethod
public void afterMethod() {
driver.quit();
}
}