I am not able to select the dropdown using selenium webdriver please - java

I am trying to select the drop down of this site and proceed to buy a show, but I am not able to do so please help.
System.setProperty("webdriver.chrome.driver", "C:/Selenium/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.theatrepeople.com/");
driver.findElement(By.id("edit-show")).click();
new Select(driver.findElement(By.id("edit-show"))).selectByVisibleText("The 39 Steps");
driver.findElement(By.id("edit-date-datepicker-popup-0")).click();
driver.findElement(By.linkText("27")).click();
driver.findElement(By.id("edit-ticket-no")).click();
new Select(driver.findElement(By.id("edit-ticket-no"))).selectByVisibleText("1 ticket");
driver.findElement(By.id("edit-submit-1")).click();

There is no reason to click on the select form (driver.findElement(By.id("edit-show")).click()), you just want to select an element (using the Select class). This is also probably the reason why your code is not working. You should remove this line and it should work.

Use the following code. It uses java script to select a text based upon it's valued. Really nice question. I also got to learn.
static WebDriver driver;
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "D:\\ToCustomer_31_5_13\\src\\main\\resources\\Drivers\\chromedriver.exe");
driver = new FirefoxDriver();
driver.get("http://www.theatrepeople.com/");
driver.findElement(By.id("edit-show")).click();
WebElement show = driver.findElement(By.xpath("//div[#id = 'edit-show-wrapper']//div[#id = 'showNameWrap']"));
List<WebElement> l = show.findElements(By.tagName("option"));
String valueToSelect = getAttibuteValueForShow(l, "The American Plan");
driver.findElement(By.id("mini-basket-ajax")).click();
selectValueInDropDown(valueToSelect);
}
public static String getAttibuteValueForShow(List<WebElement> li, String showName)
{
int j =0;
String value = null;
for(int i =0; i<li.size(); i++)
{
j = j +1;
String dropDownText = li.get(i).getText();
if(dropDownText.equalsIgnoreCase(showName))
{
value = driver.findElement(By.xpath("//div[#id = 'edit-show-wrapper']//div[#id = 'showNameWrap']//option[" + j +"]")).getAttribute("value");
System.out.println(value);
break;
}
}
return value;
}
public static void selectValueInDropDown(String value)
{
JavascriptExecutor js = (JavascriptExecutor) driver;
String jsCmd = "document.getElementsByName('show')[0].value='" + value + "'";
js.executeScript(jsCmd);
}

The following code will work
WebDriver driver = new ChromeDriver();
driver.get("http://www.theatrepeople.com/");
WebElement dropDown = driver.findElement(By.id("edit-ticket-no"));
Select sel = new Select(dropDown);
sel.selectByVisibleText("1 ticket");

Related

How To Drag And Drop the Items in Decending order using Selenium

Hi Iam new to selenium,
In URL: https://jqueryui.com/sortable/ with help of Mouse We need to sort the list. I tried this code but nothing happens any workaround in selenium how we can do this?
there are 7 items we need to sort data in descending order by mouse
I tried the below code but it's not working how can I achieve it
WebDriver driver =new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://jqueryui.com/sortable/");
driver.switchTo().frame(0);
List<WebElement> lists = driver.findElements(By.xpath("//ul[#id='sortable']/li"));
Actions a = new Actions(driver);
for(int i=0;i<lists.size();++i){
WebElement element = lists.get(i);
String text = lists.get(i).getText();
String[] values = text.split(" ");
int number = Integer.valueOf(values[1]);
}
a.clickAndHold(lists.get(0)).dragAndDrop(lists.get(0), lists.get(6)).build().perform();
a.clickAndHold(lists.get(0)).moveToElement(lists.get(3)).release().build().perform();
///////////////////////////////////////////////////////////////
for(int i =dragAndDropElement.size();i>1;i--) {
WebElement element = driver.findElement(By.xpath("((//ul[#id='sortable']/li)["+i+"])"));
//Just collected all the destination location,
WebElement destination1 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[1])"));
WebElement destination2 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[2])"));
WebElement destination3 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[3])"));
WebElement destination4 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[4])"));
WebElement destination5 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[5])"));
WebElement destination6 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[6])"));
WebElement destination7 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[7])"));
Actions action = new Actions(driver);
if(element!=null) {
action.dragAndDrop(destination1,element).perform();
action.dragAndDrop(destination2,element).perform();
action.dragAndDrop(destination3,element).perform();
action.dragAndDrop(destination4,element).perform();
action.dragAndDrop(destination5,element).perform();
action.dragAndDrop(destination6,element).perform();
action.dragAndDrop(destination7,element).perform();
break;
}
You can check with this solution, Further, you could enhance this as per your requirement and simplification. Anyway, I hope it will help you.
WebDriver driver = new ChromeDriver();
driver.get("https://jqueryui.com/sortable/");
new WebDriverWait(driver,10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[#class='demo-frame']")));
List<WebElement> dragAndDropElement = driver.findElements(By.xpath("//ul[#id='sortable']/li"));
System.out.println(dragAndDropElement.size());
for(int i =1;i<dragAndDropElement.size();i++) {
WebElement element = driver.findElement(By.xpath("((//ul[#id='sortable']/li)["+i+"])"));
//Just collected all the destination location,
WebElement destination1 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[1])"));
WebElement destination2 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[2])"));
WebElement destination3 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[3])"));
WebElement destination4 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[4])"));
WebElement destination5 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[5])"));
WebElement destination6 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[6])"));
WebElement destination7 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[7])"));
Actions action = new Actions(driver);
if(element!=null) {
action.dragAndDrop(destination7,element).perform();
action.dragAndDrop(destination6,element).perform();
action.dragAndDrop(destination5,element).perform();
action.dragAndDrop(destination4,element).perform();
action.dragAndDrop(destination3,element).perform();
action.dragAndDrop(destination2,element).perform();
action.dragAndDrop(destination1,element).perform();
break;
}
}
You can try this code:
List<WebElement> lists = driver.findElements(By.xpath("//ul[#id='sortable']/li"));
// above list holds size of 7
Actions a = new Actions(driver);
WebElement lastEle = driver.findElement(By.xpath("//li[text()='Item " + lists.size() + "']"));
// I am picking last element as we have to sort in descending order. That means 1-7, 2-7, 3-7 etc..
// At last the order should be Item 7, 6, 5, 4, 3, 2, 1.
for(int i=1;i<=lists.size() - 1;++i) {
// Here, I don't want to drag last element i.e Item 7 as it will be on top at last. That is why I am not considering 7th element to drag
WebElement elementToDrag = driver.findElement(By.xpath("//li[text()='Item " + i + "']"));
a.clickAndHold(elementToDrag).dragAndDrop(elementToDrag, lastEle).build().perform();
Thread.sleep(1000);
}

Selenium webdriver- how to print google search result description on console

Proble statement is as follows:
Open www.google.com in browser.
Add selenium hq in search
findout search result for wikipedia link for selenium hq.
print description which is displayed next to link to console.
search result is sometimes appears on 1st page and sometimes not.
i am able to search on 1st page and if its not there then traverse to 2nd page and so on.
but not able to get that description.
My code is:
WebDriver driver = null;
String baseUrl = "https://www.google.com";
System.setProperty("webdriver.gecko.driver", "C:\\SeleniumDrivers\\geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.xpath(".//input[#class='gLFyf gsfi']")).sendKeys("Selenium HQ");
driver.findElement(By.xpath(".//input[#class='gLFyf gsfi']")).sendKeys(Keys.ENTER);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
List<WebElement> linkElements = new ArrayList<WebElement>();
ListIterator<WebElement> itr = null;
WebElement toClick = null;
int pageNumber = 1;
WebDriverWait wait = new WebDriverWait(driver, 10);
boolean flag = false;
while (!flag)
{
linkElements = wait.until(ExpectedConditions
.presenceOfAllElementsLocatedBy(By
.xpath("//h3[#class='s']")));
itr = linkElements.listIterator(); // re-initializing iterator
while (itr.hasNext())
{
toClick = itr.next();
if (toClick.getText().contains("Wikidata"))
{
String desc = toClick.getText();
System.out.println(desc);
flag = true;
break;
}
}
if (!flag)
{
driver.findElement(By.xpath("//a[#id='pnnext']/span[1]")).click();
pageNumber++;
linkElements.clear(); // clean list
// wait.until(ExpectedConditions.textToBePresentInElementLocated(
//By.xpath("//div[#class='st']"), pageNumber + ""));
}
}
driver.close();
looking for a solution to this problem..

How to close a pop up window in Selenium?

I am trying to close a pop up window which is not allowing my code to execute further. But I am unable to do that. There is a a pop up window which says 'Free pound 5 voucher' which is not getting closed.
Below is my code. Please check and suggest.
public class Alldetails {
WebDriver driver;
public List<String> links1 = new ArrayList<String>();
#BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver", "C:\\Pankaj\\chromedriver.exe");
driver = new ChromeDriver();
// driver = new FirefoxDriver();
driver.manage().window().maximize();
}
#Test
public void f() {
driver.get("http://www.debenhams.com/kids/t-shirts-tops/boys");
driver.findElement(
By.xpath(".//*[#id='dijit__WidgetsInTemplateMixin_0']/div/div[1]/button"))
.click();
WebElement a = driver.findElement(By.className("products_count"));
String product_count = a.getText();
Integer x = Integer.valueOf(product_count);
System.out.println(x);
for (int i = 1; i < (x / 60) + 1; i++) {
driver.get("http://www.debenhams.com/kids/t-shirts-tops/boys" + "?pn=" + i);
List<WebElement> links = driver
.findElements(By.className("item_container").tagName("a"));
for (WebElement abcx : links) {
String ax = abcx.getAttribute("href");
// if(!links1.contains(ax))
links1.add(ax);
}
for (String b : links1) {
if (b.contains("/webapp/wcs/stores/servlet/prod"))
System.out.println(b);
}
}
}
#AfterTest
public void afterTest() {
}
}
You need to do something like this:
Alert alert = driver.switchTo().alert();
// Prints text and closes alert
System.out.println(alert.getText());
alert.accept();
or
alert.dismiss();
according to your needs.
EDIT
You may get an AlertNotPresentException if your code runs before the alert appears. In order to avoid that you may add a delay like this:
WebDriverWait wait = new WebDriverWait(driver, 15, 100)
wait.until(ExpectedConditions.alertIsPresent())
This will make Selenium wait 15 seconds checking every 100 milliseconds if the alert appeared. This snippet is not mine and had been taken from here: Selenium how to get the alert Alert message

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