Handle listbox values in Selenium Webdriver - java

I am new to Selenium. I just want to know if I am having some excel data. How can I compare it with any listbox value and select that listbox value while executing any script.
I have following code:
System.setProperty("webdriver.gecko.driver","E:/Bhavin/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
WebElement val = driver.findElement(By.id("month"));
List<WebElement> months = val.findElements(By.tagName("option"));
//System.out.println("values are "+months);
for (int i=0;i<=months.size();i++){
String value = months.get(i).getText();
//System.out.println("values for the months are "+value);
}
ArrayList<String> month = readExcel(5);
//System.out.println("months.... "+month);
Suppose I have stored an Excel column in an array list (month). How can I compare the arraylist value from Excel to the list value that I stored for f.b months and apply select command for the same.

Related

Double click on table row and insert value

I use this code to double click on table row and insert a value into input filed:
WebElement element = driver.findElement(By.xpath("/......iv[3]"));
Actions builder = new Actions(driver);
builder.doubleClick(element).perform();
Thread.sleep(3000);
// Insert into Accessorial Tasks screen Actual value
insertInputFieldByXPath(driver, "...../input",
"3");
protected void insertInputFieldByXPath(WebDriver driver, String input_id, String value){
WebDriverWait webDriverWait = new WebDriverWait(driver, 15);
WebElement webElement = webDriverWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(input_id)));
webElement.clear(); // First we delete the old value in case if this is a spinner
webElement.sendKeys(value);
}
When I double click with Selenium the table row becomes input field. But when I try to enter some value the id is not found. Maybe it's not found because the input field ID is dynamically added when I double click.
Do you know how this issue can be solved?

How to write the contents of a table to csv file using selenium java?

I have a web page with table that has more than 150 contents. But not all data is shown in a single page ie only 50 contents are shown in first page, like this the contents in the table are separated into five pages. So we first we have to get contents in the table from first page then move on to second page get the contents from table and so on.. for all four pages and write those contents in a csv file using selenium java.
So for I have tried this code , With this code I can get all data from table to csv file but my problem is when I open and check the csv file all the data's in table are appended in a single column. I need to get those data same as my table ie rows and column should be same as table
public static void main(String[] args) throws IOException, InterruptedException {
System.setProperty("webdriver.chrome.driver", "Driver path");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("Page URL");
WebDriverWait Wait = new WebDriverWait(driver, 30);
WebElement table = Wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("table-container-inner"))); //getting data from table in first page
String dataoutput;
dataoutput = table.getText();
System.out.println(dataoutput);
driver.findElement(By.xpath("//a[#aria-label='Next']")).click(); // here i am moving on to next page by clicking next option
WebElement table1 = Wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("table-container-inner")));
String dataoutput1 = table1.getText();
System.out.println(dataoutput1);
driver.findElement(By.xpath("//a[#aria-label='Next']")).click();
WebElement table2 = Wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("table-container-inner")));
String dataoutput2 = table2.getText();
System.out.println(dataoutput2);
driver.findElement(By.xpath("//a[#aria-label='Next']")).click();
WebElement table3 = Wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("table-container-inner")));
String dataoutput3 = table3.getText();
System.out.println(dataoutput3);
String tableoutput = dataoutput + dataoutput1 + dataoutput2 + dataoutput3;
String csvOutputFile = "table.csv";
try (FileWriter writecsv = new FileWriter("C:\\Natesh\\Automation\\table.csv")) {
writecsv.append(tableoutput);
}
}

I am trying to click on an option in the dropdown with the help of the li tag but not getting the output neither am i getting any error

public class CssSelector3 {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://qa.letslearnindia.com");
driver.manage().window().maximize();
driver.findElement(By.linkText("Sign in")).click();
Thread.sleep(5000);
driver.findElement(By.cssSelector("input[id='inputSuccess2']")).sendKeys("tester42#gmail.com");
driver.findElement(By.cssSelector("input[id='inputSuccess3']")).sendKeys("123456");
driver.findElement(By.cssSelector("input[id='btn_login']")).click();
Thread.sleep(5000);
driver.findElement(By.xpath("//*[#id='navbar']/ul/li[2]/a")).click();
driver.findElement(By.xpath("//*[#id='horizontalTab']/div/div[1]/div[1]/div[2]/a/input")).click();
Thread.sleep(5000);
driver.findElement(By.xpath("//*[#id='full_height_base']/div/div[3]/div[3]/div[2]/div/ul[2]/li[1]/a")).click();
driver.findElement(By.xpath("//*[#id='courseTitle']")).sendKeys("Automation Test");
driver.findElement(By.xpath("//*[#id='courseSubtitle']")).sendKeys("Automating the test cases");
Thread.sleep(5000);
WebElement dropdown = driver.findElement(By.xpath("//*[#id='validate-me-plz']/div[1]/div[2]/div/p/span"));
List<WebElement> li = dropdown.findElements(By.tagName("li"));
System.out.println(li.size());
String element;
for(int i =0; i<li.size();i++){
element = li.get(i).getAttribute("data-val");
if(element.equals("English")){
li.get(i). click();
When choosing from <select> tag you should use Select class
WebElement dropdown = driver.findElement(By.id("courseLanguage")); // locate the dropdown
Select select = new Select(dropdown); // initialize select
select.selectByVisibleText("English"); // choose the option with "English" as text
// select.selectByValue("English"); // choose the option with "English" as value
Its still giving an error as "Element is not currently visible and so may not be interacted with"
To make sure the element is visible before interaction use explicit wait
// this will wait up to 10 seconds for the dropdown to be visible and will return the dropdown element
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement dropdown = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("courseLanguage")));
Select select = new Select(dropdown);
select.selectByVisibleText("English");
try by selecting all the elements with a select tag by using findElements method
and then pass the desired element to the Select class as below :
List<WebElement> AllselectTags= driver.findElements(By.tagName("select"));
WebElement selectedElement = AllselectTags.get(0);
Select s = new Select(selectedElement);
s.selectByValue("English");

Selenium webdriver to select date

I am newbie to Selenium and not able to select date website http://www.redbus.in.
Can some one help me out? I tried to pass value to the read only text box, but it was in vain.
public static void setup() throws Exception {
System.out.println("Browser Set up start.. ");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.get("http://www.redbus.in/");
System.out.println("Browser Set up Completed ");
}
#Test
public static void SelectSrcDest() throws Exception {
System.out.println("Constructing Url to open");
driver.findElement(By.id("txtSource")).sendKeys("Bangalore");
driver.findElement(By.id("txtDestination")).sendKeys("Chennai");
driver.findElement(By.xpath("html/body/div[2]/div/section/div[1]/img")).click();
driver.findElement(By.xpath("html/body/div[2]/div/section/div[1]/img")).click();
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("window.document.getElementById('txtOnwardCalendar').setAttribute('value','27-Mar-2014')");
driver.findElement(By.xpath("html/body/div[2]/div/section/div[4]/button")).click();
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
setup();
SelectSrcDest();
}
You can use xPath to find the element by text and then use the div id & table class to choose which trip & month to pick.
For instance in order to select the date of journey:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.redbus.in");
driver.findElement(By.id("txtOnwardCalendar")).click();
By locator = By.xpath("//div[#id='rbcal_txtOnwardCalendar']" +
"/table[#class='monthTable first']" +
"//td[contains(text(), '10')]");
driver.findElement(locator).click();
would select the 10th day of the first month. If you use monthTable last as the class instead, you get 10th day of the second month. And if you change the div id into rbcal_txtReturnCalendar, you can pick a date for the return trip.
You can try the following piece of code. It works perfect
driver.findElement(By.id("DDLSource")).sendKeys("C");
driver.findElement(By.xpath("//dl[#id = 'lis']//dt[text()='Chennai']")).click();
driver.findElement(By.id("DDLDestination")).sendKeys("t");
driver.findElement(By.xpath("//dl[#id = 'dis']//dt[text()='Theni']")).click();
driver.findElement(By.className("calenImg")).click();
driver.findElement(By.xpath("//td[text()='Feb']/../..//a[text()='17']")).click();
driver.findElement(By.id("calendar1")).click();
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
driver.findElement(By.xpath("//td[text()='Feb']/../..//a[text()='20']")).click();
Try this to select the date:
driver.findElement(By.id("give id")).click();
WebElement selectElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.className("ui-datepicker-year")));
Select select = new Select(selectElement);
select.selectByValue("2012");
Thread.sleep(6000);
WebElement dateWidget = driver.findElement(By.id("ui-monthpicker-div"));
List<WebElement> columns011=dateWidget011.findElements(By.tagName("td"));
for (WebElement cell: columns011){
//Select Month
if (cell.getText().equals("Feb")){
cell.findElement(By.linkText("Feb")).click();
break;
}
}
Try to figure out the element through ID.. Its very easy to target exactly by the ID.
driver.findElement(By.id("txtOnwardCalendar")).click();
WebElement selectElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.className("monthTable first")));
Select select = new Select(selectElement);
select.selectByValue("2012");
Thread.sleep(6000);
WebElement dateWidget = driver.findElement(By.id("monthTitle"));
List<WebElement> columns011=dateWidget011.findElements(By.tagName("td"));
for (WebElement cell: columns011){
//Select Month
if (cell.getText().equals("Feb")){
cell.findElement(By.linkText("Feb")).click();
break;
}
}

How to select all list options from drop downlist loop through them selcet each option and click submit button using selenium webdriver

Here is the link to print name and meaning columns of all pages using drop down
Try to build the script for following:
1. Go to http://babynames.merschat.com/index.cgi?function=Search&origin=Sanskrit&gender=f
2. print the name and meaning columns to syso.
I was able to print page 1 as it is a default page.
Here is the code:
public class BabyNamesAndMeanings {
WebDriver driver = new FirefoxDriver();
#BeforeClass
public void setUp() {
driver.get("http://babynames.merschat.com/index.cgi?function=Search&origin=Sanskrit&gender=f");
driver.manage().window().maximize();
}
#Test
public void printBabyNamesAndMeaningsOfFirstPage() {
WebElement baby_names = driver
.findElement(By
.xpath("//tbody/tr[7]/td[3]/table[2]/tbody/tr[2]/td[2]/font/table[1]/tbody"));
List<WebElement> names = baby_names.findElements(By
.xpath("//tr/td[1]/font/a"));
List<WebElement> meanings = baby_names.findElements(By
.xpath("//tr/td[4]/font/a"));
for (int i = 0; i < names.size(); i++) {
System.out.println("Name: " + names.get(i).getText()
+ " Meaning: " + meanings.get(i).getText());
}
}
I don't know how to loop through rest of the options in the drop down list at the bottom of the page and hit submit button to print name and meaning of all the pages.
There are 100+ pages.
Thanks in advance.
The code below will do your job.
driver.get("http://babynames.merschat.com/index.cgi?function=Search&origin=Sanskrit&gender=f");
List<WebElement> pageOptions = new Select(driver.findElement(By.xpath("//select[#name='page']"))).getOptions();//Get all options in dropdown
ArrayList<String> pageDd = new ArrayList<String>();
for(WebElement eachPage:pageOptions){
pageDd.add(eachPage.getText());//Save text of each option
}
int i=1;
for(String eachVal:pageDd){
new Select(driver.findElement(By.xpath("//select[#name='page']"))).selectByVisibleText(eachVal);//Select page
driver.findElement(By.xpath("//input[#value='Go']")).click();//Click on go
List<WebElement> names = driver.findElements(By.xpath("//a[contains(#title,' meanings and popularity')]"));//Get all names on page
for(WebElement eachName:names){
String name = eachName.getText(); //Get each name's text
WebElement mean = eachName.findElement(By.xpath("./../../..//a[contains(#title,'Names for baby with meanings like ')]"));//Get meaning for that name
String meaning = mean.getText();//Get text of meaning
System.out.println(i+") Name: " +name+ " Meaning: " + meaning);//Print the data
i++;
}
}
Try and understand the way requirement is achieved. If you have any doubt ask.
Another method to iterate and select all the Dropdown values
Select dropdown= new Select(WebUIDriver.webDr.findElement(By.xpath("enter xpath")));
int noOfDropDownValues= dropdown.getOptions().size()-1;
for(int i=0;i<noOfDropDownValues;i++){
new Select(WebUIDriver.webDr.findElement(By.xpath("Enter Xpath']"))).selectByValue(String.valueOf(i));
}

Categories

Resources