简体   繁体   中英

Need Help - Count number of times the word “cheese” string appears and print number in java using selenium

Hi i'm trying to figure out how to count how many times the word "cheese" string appears and print the number using selenium. Here's what I have:

    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.bing.com");
    WebElement element = driver.findElement(By.name("q")); 
    element.sendKeys("cheese"); 
    element.submit(); 


    List <WebElement> links = driver.findElement(By.xpath("//*")).findElements(By.tagName("a"));


    for(int i = 0; i < links.size(); i++)
    {
        System.out.println("Link: " + links.get(i).getAttribute("href"));
        System.out.println("Title" + links.get(i).getAttribute("title"));
        System.out.println("Description: " + links.get(i).getText()+ "\n");
        //Trying to calculate the total count the word "cheese" from .getText()     
    }

any help is appreciated. Thank you

It should be easy if you write your selector correctly. Follow this:

By byXpath = ".//a/strong[.='cheese' or .='Cheese']" //assuming you want all the cheese ignoring case

//and then find the list and count

IList<IWebElement> list = Driver.FindElements(byXpath);
Console.WriteLine(list.Count.ToString());

Using C#

StringBuilder stringBuilder = new StringBuilder();

for(int i = 0; i < links.size(); i++) {
    stringBuilder.append(links.get(i).getText());
}

String totalResult = stringBuilder.toString();

System.out.println(totalResult.toLowerCase().split("cheese", -1).length-1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM