BullyATWiiplaza

Selenium Google Search Example

Jan 16th, 2020
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.15 KB | None | 0 0
  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.WebElement;
  4. import org.openqa.selenium.chrome.ChromeDriver;
  5.  
  6. import java.util.List;
  7.  
  8. public class Main
  9. {
  10.     public static void main(String[] arguments)
  11.     {
  12.         // Specify the ChromeDriver binary
  13.         System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
  14.  
  15.         // Create a ChromeDriver instance
  16.         WebDriver driver = new ChromeDriver();
  17.  
  18.         // Visit Google
  19.         driver.get("http://www.google.com");
  20.  
  21.         // Find the search field and enter the search term
  22.         WebElement element = driver.findElement(By.name("q"));
  23.         element.sendKeys("BullyWiiPlaza");
  24.         element.submit();
  25.  
  26.         // Find the search results
  27.         List<WebElement> searchResults = driver.findElements(By.cssSelector("#rso > div:nth-child(1) > div > div"));
  28.  
  29.         // Print the search results
  30.         System.out.println("Search Results:");
  31.         for (WebElement searchResult : searchResults)
  32.         {
  33.             WebElement searchResultURL = searchResult.findElement(By.cssSelector("div > div > div.r > a"));
  34.             System.out.println(searchResultURL.getAttribute("href"));
  35.         }
  36.  
  37.         // Quit the session
  38.         driver.quit();
  39.     }
  40. }
Add Comment
Please, Sign In to add comment