我正在使用 XPath/CSS 和 Selenium 来定位网站上的元素。我想创建一种方法,在该方法中迭代定位器列表(XPath / CSS),程序选择有效的一个。换句话说,它从定位器一开始 - 如果定位器存在,则返回 true 并存在循环。否则,它将移至列表中的下一个定位器。一旦耗尽所有 CSS 定位器,它就会转向 XPath 等等。
目前,我正在考虑按如下方式实施:
public boolean iterate(WebDriver driver, By selectorType, String[] locator)
{
driver.get("URL");
for(int selectorListCounter = 0; selectorListCounter < locator.length; selectorListCounter++) {
try
{
driver.findElement(By.(selectorType)).sendText();
System.out.println("CSS Selector: " + CSS + " found");
return true;
} catch (Exception e)
{
System.out.println(CSS + " CSS Selector Not Present");
return false;
}
}
然后我计划为每个定位器类型调用此方法(一次用于 XPath,一次用于 CSS 等)
这是最好的方法吗?
实际上我昨天这样做只是为了加快结果处理速度。
你没有成功和失败,只有选项 1 和选项 2。
该程序中每次检查元素的隐式等待时间为 1 秒。因此 while 循环总共持续 8 秒(因为它每次迭代生成两个数组)。这通过将元素放入数组中来检查元素是否存在,然后检查数组的大小,如果元素不存在,则数组将为空。然而,当这些条件之一失败时,这意味着页面上存在您的元素之一。
然后在它下面,我们设置布尔值来找出页面上存在哪些元素,并捕获不存在的元素的错误。
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
int checkForElement=1;
success = false; failure = false;
while (driver.findElements(By.className("successMessage")).size()==0 && driver.findElements(By.className("errormessage")).size()==0 && checkForElement<=4 )
{
checkForElement+=1;
}
checkForElement=1;//reset variable
try
{
@SuppressWarnings("unused")//suppresses the warning so that the class is clean
WebElement successful = driver.findElement(By.className("successMessage"));//not used practically, but logically used to look for the presence of an element without waiting the normal implicit wait time I would have at 6 seconds
success = true;
}
catch(Exception e)
{
success = false;
}
try
{
@SuppressWarnings("unused")//suppresses the warning so that the class is clean
WebElement failing = driver.findElement(By.className("errormessage"));//not used practically, but logically used to look for the presence of an element without waiting the normal implicit wait time I would have at 6 seconds
failure = true;
}
catch(Exception e)
{
failure = false;
}
if(success)
{
//run success code
}
else if(failure)
{
//run failure code
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)