获取整个html
String html_source = driver.findElement(By.xpath("//*")).getAttribute("outerHTML");
属性A包含某值,并且包含某个属性B的元素
//a[contains(@data-dom,'id:1111') and @data-testlog]
获取多个匹配节点中的第n个
(//a[contains(@href,'url=')])[1]
判断元素是否存在,存在点击cancel按钮,不存在则捕获异常点击元素B
if(msitepid.contains(pid)){
try{
driver.findElement(By.xpath("//div[contains(text(),'baidu')]")).elementExist(3);
driver.findElement(By.xpath("//div[contains(text(),'baidu')]/parent::div/descendant::div[contains(text(),'Cancel')]")).click();
TimeUtil.toWait(3000);
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}catch (NoSuchElementException e){
driver.findElements(By.xpath("这里是xpath定位")).get(0).click();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}
}
element is not attached to the page document
原因:页面刷新后需要重新定位元素
解决方法:try异常后重新捕获下元素
try {
driver.findElement(By.xpath("//a[@title='test' and contains(text(),'test')]")).click();
}catch (org.openqa.selenium.StaleElementReferenceException ex){
driver.findElement(By.xpath("//a[@title='test' and contains(text(),'test')]")).click();
}
模拟鼠标hover元素
MUIDriver driver =new MUIDriver();// 声明MUI的driver
Actions builder =new Actions(driver.getWebDriver());
WebElement logout = driver.getWebDriver().findElement(By.id("//a[@title='test' and contains(text(),'test')]"));
Action perf= builder.moveToElement(logout).build();
perf.perform();
TimeUtil.toWait(3000);
driver.getWebDriver().findElement(By.id("//a[@class='Sign Out']"));
iframe弹出浮层定位不到
登录的浮层是iframe,登录输入框嵌在iframe标签下面,需要先定位到iframe,切换到该iframe,然后再定位到输入框
StepLog.log("切换到登录iframe浮层");
WebElement iframe = driver.getWebDriver().findElement(By.id("login"));
driver.switchTo().frame(iframe);
StepLog.log("输入登录账号");
driver.getWebDriver().findElement(By.id("loginid")).sendKeys("loginaccount");
定位不到iframe,NoSuchFrameException: Message: no such frame
需要先回到主框架,然后定位到iframe,再定位到元素
StepLog.log("切换到登录消息iframe浮层");
driver.switchTo().defaultContent(); //回到主框架
driver.switchTo().frame("#web-iframe"); //进入到要定位元素被包含的那层框架,框架可以用id或者name直接定位
StepLog.log("验证消息弹框展示");
driver.findElement(By.id("chat")).elementExist(3);
获取包含某个熟悉的元素的父节点
先定位到该节点,再findElement(By.xpath(".."))
List<WebElement> we = driver.findElements(By.xpath("//tbody[@class='next-table-body']/descendant::img[@src]"));
for(int i=0;i<we.size();i++){
String href = we.get(i).getWebElement().findElement(By.xpath("..")).getAttribute("href");
}