gpt4 book ai didi

java - Selenium:遍历元素列表

转载 作者:搜寻专家 更新时间:2023-11-01 03:35:56 25 4
gpt4 key购买 nike

我正在使用 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 秒(因为它每次迭代都会生成两个数组)。这通过将元素放入数组来检查元素是否存在,然后检查数组的大小,如果元素不存在,则数组将为空。但是,当这些条件之一失败时,这意味着您的元素之一退出了页面。

然后在它下面我们设置 boolean 值来找出页面上存在这些元素中的哪些元素并捕获不存在的元素的错误。

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
}

关于java - Selenium:遍历元素列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31603764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com