Thursday, 19 June 2014

Selenium code to set google preferences and search the keywords

Below code will change the google search settings and also search some keywords.

package seleniumtest;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintStream;
import java.util.List;
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.chrome.ChromeDriver;
import org.openqa.selenium.ie.*;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public  class Google {
 
 
 public static void main(String[] args) {
 
     WebDriver driver =null;
     System.setProperty("webdriver.chrome.driver", "F:\\selenium\\csharp\\chromedriver.exe");
   driver = new ChromeDriver();
   driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
   driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
   driver.manage().window().maximize();
   
 try{
  
  driver.get("https://www.google.co.in/preferences?hl=en-IN&fg=1"); 
driver.findElement(By.xpath("//div[text()='Never show Instant results.']")).click();
driver.findElement(By.xpath("//div[text()='Save']")).click();

driver.get("https://www.google.co.in");  

//String x = driver.switchTo().frame(0).switchTo().frame(0).findElement(By.tagName("h3")).getText();
//String x = driver.switchTo().frame(1).findElement(By.tagName("h3")).getText();
//String x = driver.switchTo().frame("view").switchTo().frame(0).getPageSource();
//System.out.println(x);

String str = "Selenium How to ";
String d = "";
 
for (int i=1 ;i<=26;i++)
 
{
 char x = (char) (64+i);
 
driver.findElement(By.cssSelector("input[name=q]")).sendKeys(str + x);

Thread.sleep(2000);
List <WebElement> tr =  driver.findElements(By.xpath("//table[@class='gssb_m']//tr"));

for (int co=0 ; co<tr.size();co=co+2)
{
 
 d= d + tr.get(co).getText() + "\r\n";
}

driver.findElement(By.id("lst-ib")).clear();

}

System.out.println(d);
String filePath = "f:\\videos\\"+ str +".txt";
     
   if ((new File(filePath)).exists() )
    (new File(filePath)).delete();
     
     
 File temp = new File(filePath);
 FileWriter fw = new FileWriter(temp,true);
 fw.append(d);
 fw.close();
     


 

    Thread.sleep(4000);
    //driver.navigate();
//driver.navigate("http://www.google.com");
  
}catch(Exception e){

 //System.out.println(e.getLocalizedMessage());
   
   e.printStackTrace(new PrintStream(System.out));
   
  }
   
   
  finally{
   driver.close();
   driver.quit();
  } 
   
  
  
  
  
 }
 
 

 
}


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Buy Best Selenium Books

Contributors