我有一个网页,有时新元素是动态添加的,比如:
<span class="chat_message">| New Login</span>当上面的代码被添加到我的页面时,我该如何捕获?
我的代码试用:
WebDriver driver = new ChromeDriver () ;
driver.get("http://www.example.com") ;
// code to monitor the new span发布于 2019-02-17 14:57:55
如果你知道那个元素的定位器--有一个"while“循环,里面有一个findElement(),然后捕获NoSuchElementException。如果元素不存在,您将捕获异常,暂停一段时间(通过sleep),并开始一个新的循环周期。如果没有抛出异常,则元素存在;将while控制变量更改为true,然后继续。
我建议有一个计数器,循环运行了多少次,如果它达到了某个阈值-打破它,出现错误/异常-这样你就不会陷入无限循环。
恭喜-您刚刚使用presenceOfElementLocated() ExpectedConditions实现了WebDriverWait。你可以使用它(普通的selenium版本),或者坚持使用自己开发的解决方案,这将为你提供更细粒度的控制&决策树-但需要更多的编码。
如果您没有特定的元素,但只想查看页面本身何时发生更改,则算法是相同的,但是:在开始循环之前,获取页面源代码。在它的内部,再次获得它;如果两者不同,那就是你的突破条件。
然而,这种方法会受到页面中最轻微的更改的影响。
发布于 2019-02-17 15:01:14
请使用下面的代码片段。如果找不到匹配的元素,findElements将返回一个空列表,而不是返回异常。不过,我已经完成了异常处理。
import java.awt.AWTException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class Testing {
public static WebDriver driver;
@Test
public void test() throws InterruptedException, AWTException {
WebDriver driver = new ChromeDriver();
driver.get("http://www.example.com");
Boolean isPresent = driver.findElements(By.xpath("//span[@class='chat_message']")).size() > 0;
try {
if (isPresent == true) {
System.out.println("New Login is added to my page");
} else {
System.out.println("New Login is not added to my page");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
如果至少找到一个元素,则返回true;如果元素不存在,则返回false。
请接受答案,如果它符合您的期望,并提前做upvote.Thanks。
发布于 2019-02-18 03:05:21
当您提到需要捕获元素时,用例可以归结为使用ExpectedConditions作为visibilityOfElementLocated(By locator)来归纳WebDriverWait,这样您就可以提取任何元素属性:
在这些情况下,最佳选择是创建一个函数,如下所示:
public void getElementAttribute()
{
try {
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[@class='chat_message']"))).getAttribute("innerHTML"));
}
catch(Exception TimeoutException) {
System.out.println("Element no found");
}
}现在,您可以从程序中的任何位置调用此函数来检查元素的可见性,如下所示:
getElementAttribute();注意:
TimeoutException,您需要捕获visibilityOfElementLocated恰好适合的元素。try-catch {}块中,以防出现异常,请正确处理TimeoutException并继续您的下一步。https://stackoverflow.com/questions/54729651
复制相似问题