In this post I will give an example of how to perform search with Selenium script on a webpage. Below is the screenshot of the webpage:
Code to automatically enter a keyword “paint” in the textbox and then click Search button (or enter key) is given below. Go through the comments in the code:
package login;
import java.sql.Driver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class performsearch { public static WebDriver driver; public static void main(String[] args) { String baseUrl = "https://colored.lmscheckout.com/"; WebDriver driver = new FirefoxDriver(); driver.get(baseUrl); driver.manage().window().maximize(); // before we can search we need to login to the site driver.findElement(By.id("UserUsername")).sendKeys("abc@mailinator.com"); driver.findElement(By.id("UserPassword")).sendKeys("Abc123!"); driver.findElement(By.id("btnLoginHeader")).click(); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); //now go to target page where we need to perform the search driver.findElement(By.xpath("//a[@href='/SearchProducts/index']")).click(); driver.findElement(By.xpath("//a[@href='/SearchProducts/display']")).click(); //get hold of the textbox in which to put the text to search WebElement element = driver.findElement(By.cssSelector("input[class='']")); //enter “paint” to find out the products that contain this word element.sendKeys("paint"); //press enter key element.sendKeys(Keys.RETURN); } }
This is what we get:
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.