Multi select drop down - java

I am writing code for multi select using selenium(java) where i need the following task to be performed :
select multiple options in drop down
to click on button first selected which will print the first selected option from drop down.
to click on button get all selected which will print the all selected options in order .
I have this code which returns me undefined as a result for 2nd task.
public class MultipleSlectList {
public static WebDriver driver ;
#BeforeTest
public void startbrowser () throws Exception {
System.out.println("launching browser");
System.setProperty("webdriver.gecko.driver", "H:\\Selenium3\\geckodriver-v0.19.1-win32\\geckodriver.exe");
driver = new FirefoxDriver();
driver.get("http://www.seleniumeasy.com/test/basic-select-dropdown-demo.html");
}
#Test
public void selectlist () throws Exception {
WebElement ele1 = driver.findElement(By.id("multi-select"));
Select se= new Select(ele1);
se.selectByValue("New Jersey");
Thread.sleep(2000);
se.selectByValue("Texas");
Thread.sleep(2000);
se.selectByValue("Florida");
Thread.sleep(2000);
//Thread.sleep(10000);
WebElement btn1= driver.findElement(By.id("printMe"));
btn1.click(); // it is supposed to return New Jersy
WebElement firstOption = se.getFirstSelectedOption();
System.out.println("The First selected option is::" +firstOption.getText());
List <WebElement> oSize = se.getAllSelectedOptions();
int iListSize = oSize.size();
// Setting up the loop to print all the options
for (int i = 0; i < iListSize; i++)
{
// Storing the value of the option
String sValue = oSize.get(i).getText();
// Printing the stored value
System.out.println(sValue);
}
}
}
Please help me to proceed further.
I have tried with jquery as well but no luck .The result is same as "undefined" in both case .
Thanks !

Steps to select all dropdown options:
Find the SELECT WebElement by webdriver.
Create Select class which is used to operate dropdown list.
Get all options list in the dropdown list.
Loop the options list, get each option value and use
Select.selectByValue(optionValue) to select it.
Then all the dropdown option has been selected.
Below article has the code example to implement above scenario.
http://www.dev2qa.com/select-dropdown-list-selenium-webdriver/

Related

how to select the auto popup hotel names in a hotel booking site in Selenium

I am working on automating the following hotel booking site. I need to select the auto popup hotel name once I type the hotel in the first search box...I don't know how to do this.
I have navigated through the link and clicked Demo, then clicked the first link that appeared on the page.
I tried to click on the first search box and I need to enter a hotel from the auto popup list...I don't know how to do this because this has no PAC-item...
https://www.phptravels.net/home
public class Question1 {
WebDriver Driver = null;
WebDriverWait wait = null;
String url = "https://phptravels.com/demo/";
#BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver","src\\test\\resources\\drivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches",Arrays.asList("disable-popup-blocking"));
options.addArguments("--disable-popup-blocking");
Driver = new ChromeDriver(options);
Driver.manage().window().maximize();
Driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
wait = new WebDriverWait(Driver, 25);
String winHandle = Driver.getWindowHandle();
//Driver.switchTo().window(winHandle);
//new WebDriverWait(Driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[title='webpush-onsite']")));
//new WebDriverWait(Driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button#deny.button.close"))).click();
}
#Test
public void f() {
Driver.get(url);
System.out.println("*****In the main page*****");
String xpathDemo = "//*[#id=\"mega-nav-navigation\"]/div/ul[1]/li[2]/a";
Driver.findElement(By.xpath(xpathDemo)).click();
String Title = "PHPTRAVELS | Travel Technology Partner";
/*try {
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[#id=\"PopupSignupForm_0\"]/div[2]/div[1]")));
Driver.findElement(By.xpath("//*[#id=\"PopupSignupForm_0\"]/div[2]/div[1]")).click();
} catch(Exception e) {
System.out.println("No popup..."+ e.getMessage());
}
*/
String username = Driver.findElement(By.xpath("//*[#id=\"Main\"]/section[2]/div/div/div[2]/div/div/div[2]/div[2]/div/div[3]/div[2]/div")).getAttribute("innerText");
username = username.substring(6) ;
String password = username.substring(30);
System.out.println("Username text :"+username + "\npassword is:"+password);
Driver.findElement(By.xpath("//*[#id=\"Main\"]/section[2]/div/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/a")).click();
utils.HelperFunctions2.switchToWindow(Driver, Title);
Driver.findElement(By.xpath("//*[#id=\"s2id_autogen16\"]")).click();
Driver.findElement(By.xpath("/html/body/div[7]/ul")).click();
}
#AfterTest
public void afterTest() {
Driver.quit();
}
}
Below xpath is result of 1st hotel, changing the index it will intreact with rest of the elements.
After filing text to the hotel text box.
give Thread.sleep(2000);
use below xpath. I hope it will work
(.//ul[#class='select2-results']/following::div[#class='select2-result-label'])[2]
I have already built bots, auto image pickers and more and I have never used the By.xpath method. Classname is much easier to use!
public void f(){
Driver.get(url);
String getInputFocusId = "select2-input";
Driver.findElement(By.className(getInputFocusId).click();
//now focused!
String text = Driver.findElement(By.className("select2-match").getText();
//text is the first default search match of the list.
}
There is also a more complicated way.
In Selenium you can sendKeys to an Element.
If the input element is focused the first match is also focused.
By clicking on Enter the focused match will be searched and displayed in the input element.
Finally you have to read the data from the input Element!
public void f(){
Driver.get(url);
String getInputFocusId = "select2-input";
WebElement element = Driver.findElement(By.className(getInputFocusId);
element.click();
//element.sendKeys(Key.DOWN);
element.sendKeys(Key.ENTER);
String text = element.getText();
//this is the text of the first search match
//if you want to get the second or third just repeat sending the DOWN key.
}
IMPORTANT: Make sure to run each line delayed (200ms is a good time). This helps you finding errors... For example in the Instagram Auth Process I delayed a lot of lines, and it finally worked!
I hope my answer helps you!!!

Selenium and Java: How do I get all of the text after a WebElement

I am coding a program in Java using WebDriver and am having a little bit of trouble getting the text after the select webElement.
The HTML code for the part of the website that I want is as follows:
<select name="language" id="langSelect" style="width:100px;">
<option value="1" >Français</option>
</select>
</div>
<div id="content">
<div id="Pagination"></div>
<div id="mid">
</div>
</div>
The textbox class codes for a search bar and a drop down bar of languages
My Java code is currently able to open chrome using the chrome driver and is able to type into the search bar. I am however not able to get the text that results from the entry.
Image
In the image here, I entered "avoir" into the search bar, and I want all of the text inside the boxes after which do not seem to have any id's or names to be used inside the xpath.
Can someone please help me in finding how to get and save the text from those fields after the dropdown language menu?
Thank you in advance!
The code I have so far:
//import statements not shown
public class WebScraper {
public WebScraper() {
}
public WebDriver driver = new ChromeDriver();
public void openTestSite() {
driver.navigate().to(the URL for the website);
}
public void enter(String word) {
WebElement query_editbox =
driver.findElement(By.id("query"));
query_editbox.sendKeys(word);
query_editbox.sendKeys(Keys.RETURN);
}
public void getText() {
//List<WebElement> searchResults =
driver.findElements(By.xpath("//div[#id='mid']/div"));
// Writer writer = new BufferedWriter(new
OutputStreamWriter(new FileOutputStream("status.txt"),
"utf-8"));
//int[] index = {0};
WebElement result=driver.findElement(By.id("mid"));
System.out.println(result.getText());
}
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver", "chromedriver");
System.out.println("Hello");
WebScraper webSrcaper = new WebScraper();
webSrcapper.openTestSite();
webSrcapper.enter("avoir");
webSrcapper.getText();
System.out.println("Hello");
}
}
I have specified three approaches to extract the text from the result box. Please check all the approaches and use the required approach.
If you want to extract all the text, then you can find the element of the result box and then you can get the Text from that.
WebElement result=driver.findElement(By.id("mid"));
System.out.println(result.getText());
If you want to extract the Text based on the Section by section, then you can go with the below approach,
List<WebElement> sectionList=driver.findElements(By.xpath("//div[#id='mid']/div"));
int i=0;
for(WebElement element:sectionList){
System.out.println("Section "+i+":"+element.getText());
i++;
}
If you want to extract the text from specific section, then you can do with the below approach
List<WebElement> sectionList=driver.findElements(By.xpath("//div[#id='mid']/div"));
int i=0;
//Inorder to get the Section 3 Content
int section=2;
for(WebElement element:sectionList){
if(section==i){
System.out.println("Section "+i+":"+element.getText());
}
i++;
}
Edit: To address followup question
I would suggest to use some explicit wait after doing some action which resulting in some element rendering. In your code, after doing some modification, I am getting the result as expected.
In openTestSite method, I have just added the explicit wait to ensure the page load after loading the URL
In enter method, actually you are getting the autocomplete suggestion after entering the query value .So, we need to just select the value from the autocomplete.
In getText method, Search result is taking more time.So, we need to add some explicit wait using any one of the dynamically loading element locator.
Code:
openTestSite Method:
public void openTestSite() {
//driver.navigate().to(the URL for the website);
driver.get("https://wonef.fr/try/");
driver.manage().window().maximize();
//Explicit wait is added after the Page load
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.titleContains("WoNeF"));
}
enter Method:
public void enter(String word) {
WebElement query_editbox =
driver.findElement(By.id("query"));
query_editbox.sendKeys(word);
//AutoComplete is happening even after sending the Enter Key.
// So, Value needs to be selected from the autocomplete
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#class='autocomplete']/div")));
List<WebElement> matchedList=driver.findElements(By.xpath("//div[#class='autocomplete']/div"));
System.out.println(matchedList.size());
for(WebElement element : matchedList){
if(element.getText().equalsIgnoreCase(word)){
element.click();
}
}
//query_editbox.sendKeys(Keys.RETURN);
}
getText Method:
public void getText() {
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#id='mid']/div")));
WebElement result=driver.findElement(By.id("mid"));
System.out.println(result.getText());
}
I have tested with the above modified code and it is working fine.
In order to inspect the relevant results for your query, common strategy would be to load a list of search results:
List<WebElement> searchResults = driver.findElements(By.xpath("//div[#id='mid']/div"));
Now you can use stream to iterate over the list and extract your relevant text, by getting the text from child elements of each result:
int[] index = {0};
searchResults.stream().forEach(result -> {
System.out.println("Printing query result of index: " + index[0]);
result.findElements(By.xpath(".//*")).stream().forEach(webElement -> {
try {
System.out.println(webElement.getText());
} catch (Exception e) {
// Do nothing
}
});
index[0]++;
});
And you would get the output:

how to select the drop down box in selenium web driver

Select se = new Select(driver.findElement(By.xpath(".//*[#id='33629']/div/div[1]/div[2]/div[1]/select")));
se.selectByIndex(7);
driver.findElement(By.xpath(".//*[#id='33629']/div/div[1]/div[2]/div[1]/select/option[8]")).click();
Above code doesn't work,please help
Error returned:
Exception in thread "main" org.openqa.selenium.NoSuchWindowException: no such window: target window already closed from unknown error: web view not found
org.openqa.selenium.NoSuchWindowException: no such window
Means the browser is close when you are trying to interact with it. Remove driver.close() from your code and put it only after you have finished all you interactions with the browser.
Edit
If you need to return to parent window after closing child window use driver.switchTo() again
// get parent window ID
String parentHandle = driver.getWindowHandle();
// switch to the new window
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(parentHandle))
{
driver.switchTo().window(handle);
}
}
//do something with the new window
// switch back to the old window
driver.close();
driver.switchTo().window(parentHandle);
windowIdbefore = driver.getWindowHandle();
System.out.println(windowIdbefore);
Set<String> windowid = driver.getWindowHandles();
for (String string : windowid) {
System.out.println(string);
driver.switchTo().window(string);
// enter code here
}
WebDriver driver=new FirefoxDriver();
Select s=new Select(driver.findElement(By.xpath("xpathExpression")));
s.selectByVisibleText("text");
s.selectByValue("value");
s.selectByIndex(1);
as i see here the dropdown box is present in div tag. i think with your code dropdown has been located but you are not able to select the value present in dropdown. Then follow below code
WebDriverWait wait = new WebDriverWait(d, 10);
Actions builder = new Actions(d);
WebElement selectvalue = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("your drop down xpath value")));
builder.mouse.mouseMove(((Locatable)selectvalue).coordinates);
selectvalue.click();
WebElement option = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("locator value of dropdown value(your dropdown value)")));
builder.mouse.mouseMove(((Locatable)option).coordinates);
option.click();
System.out.println("dropdown value slected...");

How to Verify Check-box is/are checked or Unchecked in selenium webdriver

I am doing an automation testing of one application and I am facing one scenario to verify Check-box are checked or not using automation code
my web application is developed in angular js and developer used Checked attribute
I tried with .isselected but it was not working for me.
You could use a selector that includes the ".ng-not-empty" or "ng-empty" class:
List<WebElement> eltsUnchecked = driver.findElements(By.cssSelector("input[ng-model='checkboxModel.value1'].ng-empty"));
bool isNotCheched = eltsUnchecked.size() > 0;
if (isNotCheched) {
// check the checkbox
eltsUnchecked.get(0).click();
}
List<WebElement> eltsChecked = driver.findElements(By.cssSelector("input[ng-model='checkboxModel.value1'].ng-not-empty"));
bool isCheched = eltsChecked.size() > 0;
if (isCheched) {
// uncheck the checkbox
eltsChecked.get(0).click();
}
Or by checking the presence of ".ng-not-empty" or "ng-empty" in the class attribute :
WebElement checkbox = driver.findElement(By.cssSelector("input[ng-model='checkboxModel.value1']"));
bool isCheched = checkbox.getAttribute("class").contains("ng-not-empty");
bool isNotChecked = checkbox.getAttribute("class").contains("ng-empty");
if (isCheched) {
// uncheck the checkbox
checkbox.click();
} else if (isNotChecked) {
// check the checkbox
checkbox.click();
}
But if you are using the "checked" attribute instead then:
WebElement checkbox = driver.findElement(By.cssSelector("input[ng-model='checkboxModel.value1']"));
bool isCheched = checkbox.getAttribute("checked").length > 0;
bool isNotChecked = checkbox.getAttribute("checked").length == 0;
Hi when you want to verify if a Check-box is selected or not then please pay attention that any input tag with type checkbox has a hidden attribute value known as selected if a Check-box is selected then its value is = True and if not then its value is = null,hence on the basis of this you can easily identify which Check-box is selcted or not .below find a working example for the same :
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("C:\\Users\\rajnish\\Desktop\\myCheckox.html");
// working with check boxes
// first take all the check boxes inside a list like below
List<WebElement> mycheckBox = driver.findElements(By.xpath("//*[#type='checkbox']"));
// apply the for loop to identify/ verify if a check boxes is selected or not
for(int i=0;i<mycheckBox.size();i++){
System.out.println("attribut value Selected of Check-box is : " + mycheckBox .get(i).getAttribute("selected"));
// if Check-box is selected then value of selected attribute is True else null
if( mycheckBox.get(i).getAttribute("selected").equals("null")){
// if loop will only run when value of selected attribute is null
// i.e only when Check-box is not selected
mycheckBox .get(i).click();
}
}
Use is selected function
WebElement el = driver.findElement(By.id("element Id"));
el.click()
el.isSelected()
Use isSelected instead of isselected as shown in the following code.
Assert.assertEquals(wd.findElement(By.[your element locater])).isSelected(),true);
I have successfully used it in my code and its working fine. as below:
Assert.assertEquals(wd.findElement(By.xpath("//input[#id='chkremember']")).isSelected(),true);

creating gmail account using selenium

Not able to Select the month for Date of Birth.
Code I am using is:
driver.findElement(By.xpath(".//*[#id = 'BirthMonth']/div")).click();
Thread.sleep(3000);
WebElement months = driver.findElement(By.xpath(".//[#id='BirthMonth']/div[2]/div[#id=':1']"));
Thread.sleep(2000);
months.click();
I also tried with by using DropDownList case. But Not able to set any Month.
Please Say me the Solution.
You can use keyboard event replace mouse.
WebElement birthMonth = driver.findElement(By.id("BirthMonth"));
birthMonth.click();
Actions action = new Actions(driver);
action.sendKeys(Keys.DOWN).sendKeys(Keys.ENTER).perform();
We can use sendKeys directly:
driver.findElement(By.xpath(".//*[#id='BirthMonth']/div[1]")).sendKeys("July");
You can wrap this up in a function
public void selectBirthMonth(int monthIndex)
{
driver.findElement(By.cssSelector("#BirthMonth > div")).click();
driver.findElements(By.cssSelector("#BirthMonth > div.goog-menu > div.goog-menuitem")).get(monthIndex - 1).click();
}
and then call it like
selectBirthMonth(9); // 1 = January
WebElement month = wd.findElement(By.xpath("//[#id=\"BirthMonth\"]/div[1]"));
month.click();
Thread.sleep(3000);
//wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//fetch months from the dropdown and store it in a list
List<WebElement> month_dropdown = wd.findElements(By.xpath("//[#id=\"BirthMonth\"]/div[2]/div/div"));
//iterate the list and get the expected month
for (WebElement month_ele:month_dropdown){
String expected_month = month_ele.getAttribute("innerHTML");
// Break the loop if match found
if(expected_month.equalsIgnoreCase("August")){
month_ele.click();
break;
}
}
It is not drop down value , you have to click on drop down arrows and then click on any value which you have to pass from script.
Code is below:
System.setProperty("webdriver.chrome.driver", "E:/software and tools/chromedriver_win32/chromedriver.exe");
WebDriver driver= new ChromeDriver();
//FirefoxDriver driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://accounts.google.com/SignUp");
Thread.sleep(5000);
driver.findElement(By.xpath(".//*[#id='BirthMonth']/div[1]/div[2]")).click();
driver.findElement(By.xpath(".//*[#id=':7']/div")).click();
it is workable code for Birthmonth
Please find below link for same type of Question
Not able to select the value from drop down list by using Select method in Selenium

Categories

Resources