我有一个网页,有时会像这样动态添加新元素:
<span class="chat_message">| New Login</span>
将以上代码添加到我的页面后,如何捕获?
我的代码试用版:
WebDriver driver = new ChromeDriver () ;
driver.get("http://www.example.com") ;
// code to monitor the new span
答案 0 :(得分:1)
如果您知道该元素的定位符-可以在其中有一个findElement()
的“ while”循环中捕获NoSuchElementException
。如果该元素不存在,您将捕获该异常,暂停一段时间(尽管sleep
),然后将开始一个新的循环周期。如果未引发异常,则存在元素。将您的while控制变量更改为true
,然后继续。
我建议您有一个计数器,该循环运行了多少次,并且如果达到某个阈值-会由于错误/异常而超出阈值-这样您就不会陷入无限循环中。
恭喜-您刚刚使用WebDriverWait
ExpectedConditions实现了presenceOfElementLocated()
。您可以使用它(香草硒版本),或者坚持使用自己开发的解决方案,这将为您提供更精细的控制和决策树-但需要更多的编码。
如果您没有特定的元素,而只想查看页面本身何时更改,则算法是相同的,但是:在开始循环之前,请获取页面源代码。在它的体内,再次得到它;如果两者不同,那就是您的突破条件。
不过,此方法将受到页面上任何细微变化的影响。
答案 1 :(得分:0)
请使用以下代码段。 如果没有找到匹配的元素而不是异常,则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。
如果答案符合您的期望,请接受,并进行投票。谢谢。
答案 2 :(得分:0)
当您提到您需要捕获元素时,将用例归结为以 ExpectedConditions 作为 WebDriverWait visibilityOfElementLocated(By locator)
,因此您可以提取任何元素属性:
在这些情况下,最好的选择是创建一个函数,如下所示:
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();
注意:
try-catch {}
块中,以防万一出现异常,可以妥善处理 {{1 }} ,然后继续下一步。