java - 如何查找元素直到出现在结果中
问题描述
我想自动化一个场景,我需要寻找一个元素,直到它出现在结果中,然后单击它。一旦单击它,它将打开一个新窗口。
我做错了什么或我在这里错过了什么?
<div class="result-container">
<div class="thumbnail" style="">
<img src="/app/static/img/br_news.png">
</div>
<div class="result-content">
<div class="header">
<img class="icon" src="/app/static/img/lexis-sm.png">
<h1 class="title" title="Philips India launches awareness campaign on the World Asthma Day">
Philips India launches awareness campaign on the World Asthma Day
</h1>
代码:
@FindBy(how=How.XPATH,using="//div[@class='result-container']")
public List<WebElement> allResultsContainer;
@FindBy(xpath="//div[@class='results']/div[@class='search-results']//div[@class='result-content']")
public static WebElement NewsResults;
@FindBy(xpath="//span[@class='label']")
public static WebElement searchAuthor;
public void searchforauthoronline() throws InterruptedException {
for(WebElement resultElement : allResultsContainer) {
log.info("Clicking on original article from search result.");
resultElement.click();
waitHelper.WaitForElement(searchAuthor, 10);
boolean visibility = searchAuthor.isDisplayed();
if(visibility){
searchAuthor.click();
}
else{
System.out.println("Element not present in search result");
}
}
解决方案
你在开始循环之前等待吗?
您并没有在问题中真正解释,但根据您的评论,循环只迭代一次。我猜是因为在调用该方法时只有一个元素可以迭代。
您的问题意味着您需要等待元素出现,在这种情况下,for
循环是该工作的错误工具。您可能应该使用一个do/while
不断循环的循环,直到找到可以跳出循环的元素。
我还建议添加一个故障安全条件,以便循环不会永远运行。
在伪代码中,它看起来像这样:
boolean found = false;
int counter = 0;
do {
sleep for a second
check the page for all the elements
if (correctElement.isDisplayed()) {
correctElement.click();
found = true;
}
counter++;
} while !found && counter <= 30
还会有更多内容,例如重新检查页面中的所有元素并确定正确的元素,但您应该明白这一点。
推荐阅读
- c# - 使用扩展方法将协变接口解构为 ValueTuples 时的奇怪行为
- angular - How to get id from adress path in Angular
- node.js - webpack 构建中缺少子模块的依赖项
- tcl - 获取脚本文件时如何传递参数
- java - ActionListener 和 ActionEvent 问题
- android - 自定义 ListView 适配器中的 ImageButton
- ios - iOS - 本地化静态常量
- python - 最小化 Rosenbrock 函数 mu,lambda ES 策略收敛
- python - 如何修复类型错误:在 Python 中工作时冒泡排序列表时出现“列表”对象不可调用错误
- php - 如何将工匠添加到我的包中并改进我的 Laravel 包开发工作流程?