首页 > 解决方案 > 如何查找元素直到出现在结果中

问题描述

我想自动化一个场景,我需要寻找一个元素,直到它出现在结果中,然后单击它。一旦单击它,它将打开一个新窗口。

我做错了什么或我在这里错过了什么?

    <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"); 
        }
    }

标签: javaselenium-webdriver

解决方案


你在开始循环之前等待吗?

您并没有在问题中真正解释,但根据您的评论,循环只迭代一次。我猜是因为在调用该方法时只有一个元素可以迭代。

您的问题意味着您需要等待元素出现,在这种情况下,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

还会有更多内容,例如重新检查页面中的所有元素并确定正确的元素,但您应该明白这一点。


推荐阅读