Ctrl+F search on webpage

118 views
Skip to first unread message

Mohamed Irsath

unread,
Apr 10, 2024, 10:19:11 PM4/10/24
to Selenium Users
Hi Team,

      I am stucking with the scenario where I need to perform ctrl+f search to find a keyword on a webpage and get the count of matching keywords using Selenium Java. I have used multiple ways to achieve this, but I am not able to get the results accurately as it is a dynamically loading page. Please help me to complete this assignment. This is very important for my client project

Thanks & Regards,
Mohamed Irsath M.N

Sir Jo

unread,
Apr 11, 2024, 1:04:00 AM4/11/24
to Selenium Users
Please give us an example link of a webpage, an example word to search and the results that you want

Nortier David

unread,
Apr 11, 2024, 2:52:19 AM4/11/24
to seleniu...@googlegroups.com

Hello

 

Instead of doing "CTRL+F", why not search for all the elements that contain the desired text yourself?

 

Find by Xpath : //*[contains(text(),’whatyousearch’)]

 

 

David

 

 

De : seleniu...@googlegroups.com <seleniu...@googlegroups.com> De la part de Sir Jo
Envoyé : jeudi 11 avril 2024 07:04
À : Selenium Users <seleniu...@googlegroups.com>
Objet : [selenium-users] Re: Ctrl+F search on webpage

 

ATTENTION : cet e-mail provient d'une personne externe. Vérifiez toujours l’expéditeur avant d’ouvrir les pièces jointes ou de cliquer sur les liens.

--
You received this message because you are subscribed to the Google Groups "Selenium Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to selenium-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/selenium-users/9543797b-8c16-4cd1-96ef-19d6770596d9n%40googlegroups.com.


====== DISCLAIMER ======

https://www.cph.be/maildisclaimer

Mohamed Irsath

unread,
Apr 16, 2024, 2:40:11 AM4/16/24
to Selenium Users
Hi all,

    I have successfully found the way to achieve the results. Please utilise this code for your future reference
    package PageEvents;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.awt.*;
import java.awt.event.KeyEvent;

public class InitializationPage {
WebDriver driver;

public InitializationPage(WebDriver driver) {
this.driver = driver;
}

@Test
public void GotoURL() throws InterruptedException, AWTException {
try {
WebDriverWait wait = new WebDriverWait(driver, 10);
// Load Excel file
FileInputStream file = new FileInputStream(new File(
"C:\\Users\\mohamed.israth\\Multiple workspace\\SEOAutomation\\com\\test\\utility\\TestDD.xlsx"));
Workbook workbook = new XSSFWorkbook(file);
// Get the first sheet
Sheet sheet = workbook.getSheetAt(0);

// Iterate through rows
for (Row row : sheet) {
// Get the cell containing URL (assuming URL is in the first column)
String URL = row.getCell(0) != null ? row.getCell(0).getStringCellValue() : "";
String Keyword1 = row.getCell(1) != null ? row.getCell(1).getStringCellValue() : "";
String Keyword2 = row.getCell(2) != null ? row.getCell(2).getStringCellValue() : "";
System.out.println(URL);
System.out.println(Keyword1);
System.out.println(Keyword2);
driver.get(URL);
int timeoutInSeconds = 30;
driver.manage().timeouts().implicitlyWait(timeoutInSeconds, TimeUnit.SECONDS);
Robot robot = new Robot();
scrollToBottom(driver);
performCtrlFSearch(robot, Keyword1, 1);
int keywordCount1 = countKeywordOccurrences(driver, Keyword1);
System.out.println("Number of matching keywords: " + keywordCount1);
Thread.sleep(3000);
scrollToBottom(driver);
performCtrlFSearch(robot, Keyword2, 2);
Thread.sleep(3000);
int keywordCount2 = countKeywordOccurrences(driver, Keyword2);
System.out.println("Number of matching keywords: " + keywordCount2);
}
workbook.close();
file.close();
}
catch (IOException e) {
e.printStackTrace();
}
}

public static void scrollToBottom(WebDriver driver) {
// Get the current page height
long pageHeight = (Long) ((JavascriptExecutor) driver).executeScript("return document.body.scrollHeight");

// Initialize JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;

// Scroll down to the bottom of the page
for (long currentHeight = 0; currentHeight <= pageHeight; currentHeight += 100) {
js.executeScript("window.scrollTo(0, " + currentHeight + ");");
// Adjust the sleep time as needed
try {
Thread.sleep(100); // Adjust the sleep time as needed
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void performCtrlFSearch(Robot robot, String searchQuery, int numFindBarCloses) throws InterruptedException {
    for (int i = 0; i < numFindBarCloses; i++) {
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_F);
        robot.keyRelease(KeyEvent.VK_F);
        robot.keyRelease(KeyEvent.VK_CONTROL);
       
        // Simulate typing the search query
        typeString(robot, searchQuery);
       
        // Wait for a brief moment before closing the find bar
        Thread.sleep(2000); // Adjust the delay as needed
       
        // Close the find bar by pressing the Escape key
        robot.keyPress(KeyEvent.VK_ESCAPE);
        robot.keyRelease(KeyEvent.VK_ESCAPE);
       
        // Additional delay if needed
        Thread.sleep(1000);
    }
}


public static void typeString(Robot robot, String str) {
for (char c : str.toCharArray()) {
// Convert character to its corresponding KeyEvent code
int keyCode = KeyEvent.getExtendedKeyCodeForChar(c);

// Press and release the key
robot.keyPress(keyCode);
robot.keyRelease(keyCode);
}
}

public static int countKeywordOccurrences(WebDriver driver, String keyword) {
// Wait for the page to load completely
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.tagName("body")));
String pageText = driver.findElement(By.tagName("body")).getText();
        pageText = pageText.toLowerCase(Locale.ENGLISH);
int count = countOccurrences(pageText, keyword);
return count;
}

// Function to count occurrences of a substring in a string
public static int countOccurrences(String text, String searchString) {
int count = 0;
int index = text.indexOf(searchString);
while (index != -1) {
count++;
index = text.indexOf(searchString, index + 1);
}
return count;
}
}

      Keep coding and sharing here. Thanks a lot to all for your help!

Reply all
Reply to author
Forward
0 new messages