java - 如果找不到元素则继续,如果找到则保存它
问题描述
我有一个循环,我一个一个打开链接。在这个循环中,我有 if 语句,它检查:
- 如果我看到名字,然后我复制它
如果我没有看到名字,那么我会忽略它并继续循环。
List<WebElement> demovar = driver.findElements(By.xpath("//*[@id=\"big_icon_view\"]/ul/li/p/a")); System.out.println(demovar.size()); ArrayList<String> hrefs = new ArrayList<String>(); for (WebElement var : demovar) { System.out.println(var.getText()); System.out.println(var.getAttribute("href")); hrefs.add(var.getAttribute("href")); } int i = 0; for (String href : hrefs) { driver.navigate().to(href); System.out.println((++i) + ": navigated to URL with href: " + href); if(driver.findElement(By.xpath("//a[@id='name']")).isDisplayed()) { System.out.println("I can see Name"); } else { System.out.println("I cant see Name"); } Thread.sleep(3000); // To check if the navigation is happening properly. }
为什么这不能正常工作?正如我所假设的,它应该具有以下内容:
- 如果显示元素,那么我可以看到名称
- 否则不显示元素,然后我看不到名称。
解决方案
我不确定您在此处看到什么错误消息,但如果您的代码不起作用,那么很可能该元素没有显示在页面上,因此您在尝试定位它时会收到异常。
您可以捕获NoSuchElementException
以处理元素未出现在页面上的情况。
for (String href : hrefs) {
driver.navigate().to(href);
System.out.println((++i) + ": navigated to URL with href: " + href);
// create isDisplayed variable
boolean isDisplayed = true;
try {
isDisplayed = driver.findElement(By.xpath("//a[@id='name']")).isDisplayed();
}
catch(NoSuchElementException) {
isDisplayed = false;
}
// do something else here with isDisplayed
if (isDisplayed) { System.out.println("I can see Name"); }
else { System.out.println("I can not see Name"); }
}
这段代码做的事情几乎和你的一样,但是NoSuchElementException
如果元素没有出现在页面上,我们会捕捉到被抛出的内容。
如果这对您不起作用,请随时发布您在代码中看到的错误消息或结果,这将有助于追查问题。
推荐阅读
- javascript - 我正在使用 window.fetch 下载文件,但在服务器上生成错误文件而不是在本地
- html - 模态弹出窗口未打开
- c# - sqlcmd 在 MSI 安装程序项目上不返回任何值,而它通常返回安装程序类之外的值
- dotnetnuke - DNN 升级 - Portal.css 未加载
- here-api - 在发送超过 250 个航点到 calculateroute.json 时获得 414 Request-URI Too Large
- json - 从 SectionList 中选择项目并将其与 Redux 状态同步的最佳方式/模式?(详情见正文)
- javascript - 多重长/高/宽计算器
- azure - Azure 管道的并行化
- angular - 发生http错误时的角度http处理json响应
- typescript - ESLint、TypeScript、Vue 和 WebPack Encore:无法禁用 ESLint 规则