Get value of the selected item from dropdownlist using jsoup - java

`<div class="col1">
<strong>
<select name="Category" multiple size="4">
<option value="A">A
<option value="B" selected>B
<option value="C">C
<option value="D">D
</select></strong>
</div>`
I have div class containing a drop down list as given above, i just need the value of 'selected' item from the drop down list using Jsoup

Search for the <select> Element, iterate over it’s children and check if the selected attribute is present:
Document doc = Jsoup.parse("your html")
String selectedVal = null;
Elements options = doc.getElementsByAttributeValue("name", "Category").get(0).children();
for (Element option : options) {
if (option.hasAttr("selected")) {
selectedVal = option.val();
}
}
Or in short with a CSS-like selector:
String selectedVal = doc.select("select[name=Category] option[selected]").val();

Related

Selecting DropDown from list, the option has <Space>

public static WebElement residentialStatus(String name) {
element = LoginPage.driver.findElement(By.xpath("PATH"));
Select oSelect = new Select(element);
oSelect.selectByVisibleText(name);
System.out.println("Residential Status: " + name);
return element;
}
the HTML is:
<select name="residentialStatus">
<option value="">--Please Select--</option>
<option value="B">Boarding</option>
<option value="O">Home Owner</option>
<option value="P">Living with Relative</option>
<option value="R">Renting</option>
In the above code, I am trying to select a Dropdown,
When I am selecting 'Home Owner' it fails (possible because there is a Space), when I choose 'Boarding' or 'Renting' then it works fine.
I am unable to understand where I am going wrong.
(Feeding Data from Excel, so I can't change it to 'selectByArray as all other dropdowns are working fine from the same excel)

Read option text from drop down values in selenium

List<WebElement> statusvalues = driver.findElements(By.id("ddlStatus"));
for (WebElement option : statusvalues)
{
System.out.println(option.getText());
}
This is the script I have used to write.
System not providing the error but I didn't get the result. There are five drop down values I need to write in the output. The HTML code is given below.
<select id="ddlStatus" name="Status" class="full-width" data-role="dropdownlist" style="display: none;">
<option value="" selected="selected"> -- Select -- </option>
<option value="11">Arts</option>
<option value="13">Science</option>
<option value="14">Engineering</option>
<option value="64">Law</option>
<option value="85">Teaching</option>
<option value="87">Journalist</option>
</select>
Just exploring the selenium webdriver and how to write the drop down values in the output.
List<WebElement> statusvalues = driver.findElements(By.id("ddlStatus"));
it's an element and not collection of elements so you need to do:
WebElement selectElement = driver.findElement(By.id("ddlStatus"));
In that element you have options so you can make collection:
List<WebElement> options = selectElement.findElements(By.tagName("option"));
and now you can loop...
Try:
List<WebElement> statusvalues = driver.findElement(By.id("ddlStatus")).findElements(By.tagName("option"));
for (WebElement option : statusvalues)
{
System.out.println(option.getText());
}
For the best way you should try using Select for drop down as below :-
Select sel = new Select(driver.findElement(By.id("ddlStatus")));
List<WebElement> options = sel.getOptions();
for (WebElement option : options)
{
System.out.println(option.getText());
}
Note:- driver.findElements(By.id("ddlStatus")); only provides you the list of all Elements which has id ddlStatus so in this case you could get only the drop down element here not it's option.
Hope it will help you..:)
Also you can try this
List <WebElement> options = driver.findElements(By.xpath("//*[#id='ddlStatus']/option"));
for(WebElement option : options)
{
System.out.println(option.getText());
}
You can also handle the dropdowns in 3 other ways as follows,
new Select(driver.findElement(By.id("ddlStatus"))).selectByVisibleText("Particular Text");
new Select(driver.findElement(By.id("ddlStatus"))).selectByIndex(Particular index);
new Select(driver.findElement(By.id("ddlStatus"))).selectByValue("Particular value");

How to compare the drop down options is matching with the UI options in Selenium WebDriver?

Currently working on Selenium WebDriver and using Java for scripting.
I have stored all drop down values of db in property file and want to compare same values whether they are in UI as in DropDown options.
The visualization.txt which is in C: directory contains the below options
visualizationId=Day,Week,Month,Quarter,Semester,Year,RD Tech Group,ICC,Center,Software Pack,Product,Project,Customer PRs,Severity ,Priority.
So How can I compare both values are matching. I need to get all the drop down options from property file i.e visualization.txt then need to check in the drop drop down in UI.
<select id="visualizationId" style="width: 120px; display: none;" name="visualization">
<option value="day">Day</option>
<option value="week">Week</option>
<option selected="" value="month">Month</option>
<option value="quarter">Quarter</option>
<option value="semester">Semester</option>
<option value="year">Year</option>
<option value="techgroup">RD Tech Group</option>
<option value="icc">ICC</option>
<option value="center">Center</option>
<option value="softwarepack">Software Pack</option>
<option value="product">Product</option>
<option value="project">Project</option>
<option value="customer">Customer PRs</option>
<option value="severity">Severity</option>
<option value="priority">Priority</option>
</select>
Try the following piece of code. Should help:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
BufferedReader in = new BufferedReader(new FileReader("C:\\visualization.txt"));
String line;
line = in.readLine();
in.close();
String[] expectedDropDownItemsInArray = line.split("=")[1].split(",");
// Create expected list :: This will contain expected drop-down values
ArrayList expectedDropDownItems = new ArrayList();
for(int i=0; i<expectedDropDownItemsInArray.length; i++)
expectedDropDownItems.add(expectedDropDownItemsInArray[i]);
// Create a webelement for the drop-down
WebElement visualizationDropDownElement = driver.findElement(By.id("visualizationId"));
// Instantiate Select class with the drop-down webelement
Select visualizationDropDown = new Select(visualizationDropDownElement);
// Retrieve all drop-down values and store in actual list
List<WebElement> valuesUnderVisualizationDropDown = visualizationDropDown.getOptions();
List<String> actualDropDownItems = new ArrayList();
for(WebElement value : valuesUnderVisualizationDropDown){
actualDropDownItems.add(value.getText());
}
// Print expected and actual list
System.out.println("expectedDropDownItems : " +expectedDropDownItems);
System.out.println("actualDropDownItems : " +actualDropDownItems);
// Verify both the lists having same size
if(actualDropDownItems.size() != expectedDropDownItems.size())
System.out.println("Property file is NOT updated with the drop-down values");
// Compare expected and actual list
for (int i = 0; i < actualDropDownItems.size(); i++) {
if (!expectedDropDownItems.get(i).equals(actualDropDownItems.get(i)))
System.out.println("Drop-down values are NOT in correct order");
}
//Read the data from property file
String options = property.getProperty("visualizationId");
//read the options from drop down in UI
List<WebElement> dropdownOptions = new Select(driver.findElement(By.id("visualizationId"))).getOptions();
String uiOptions="";
for(WebElement eachOption : dropdownOptions ) {
uiOptions+=eachOption.getText()+",";
if(!options.contains(eachOption.getText())) {
System.out.println(eachOption.getText()+" is present in UI but not in property file");
}
}
for(String eachOptionFromPropertyFile : options.split(",")){
if(!uiOptions.contains(eachOptionFromPropertyFile)) {
System.out.println(eachOptionFromPropertyFile+" is present in property file but not in UI");
}
}

How to select the value from dropdown box in selenium webdriver

Below having my code.I need to select the option values like value1,value2..
<td class="column-label" width="50%">
<div id="divRawMaterials" name="Companies" style="position: relative">
<select name="yieldStandardDTO.rawMaterialName" size="1" onmouseover="dropdowntooltip(this);" onmouseout="return nd();"
nmousedown="showtooltip(this);" onchange="chooseYieldItems('name');" style="width:205px;" class="select"><option value="">-- Select --</option>
<option value="010080159">value1</option>
<option value="010080024">value2</option>
<option value="010080071">value3</option>
<option value="010030014">value4</option>
<option value="010090009">value5</option>
And
I tried below methods but it doesn't work.Pls help me out of this.
METHOD:1
Select dropdown = new Select(driver.findElement(By.name("yieldStandardDTO.rawMaterialName")));
System.out.println(dropdown);
//dropdown.selectByVisibleText("value1");
//dropdown.selectByIndex(1);
dropdown.selectByValue("value1");
METHOD:2
WebElement selectMonth = driver.findElement(By.xpath("//div[#id='divRawMaterials']/select"));
List<WebElement> options = selectMonth.findElements(By.tagName("value1"));
for (WebElement option : options) {
if("Alphonso Mango".equals(option.getText()))
option.click();
METHOD:3
WebElement hiddenWebElement =driver.findElement(By.xpath("//div[#id='divRawMaterials']/select"));
((JavascriptExecutor)driver).executeScript("arguments[0].click()",hiddenWebElement);
For the drop down to appear you can try the following :
((JavascriptExecutor)driver).executeScript("$('select[name=\"yieldStandardDTO.rawMaterialName\"]').click();");
Now that the drop down is visible, you can use :
Select dropdown = new Select(driver.findElement(By.name("yieldStandardDTO.rawMaterialName")));
dropdown.selectByVisibleText("value1");

How to check that the options in dropdown are displayed twice in Selenium Webdriver using Java

I am stuck in one logic, where I have to verify if the options in dropdown are displaying twice. I searched in google for the solution, but didnt find any.
I have this code to get all the options from the dropdown. But not really sure how should I check if the options are displayed twice.
new Select(driver.findElement(By.xpath(//*[#id='unmappedTech']))).selectByVisibleText(VisibleText);
new Select(driver.findElement(By.xpath(//*[#id='unmappedTech']))).getOptions();
In my application, options are displaying twice in dropdown. Here is the source code of dropdown:
<table><tbody><tr>
<td>
<select name="unmappedTech" id="unmappedTech" multiple="multiple" size="10" style="width: 160px;">
<option class=" firepath-matching-node" value="142">Cloud Service Assurance</option>
<option value="123">Cloud Service Assurance Zenoss for Data Center and Cloud</option>
<option value="6">CUSTOMER COLLABORATION</option>
<option value="12">DESKTOP VIRTUALIZATION</option>
<option value="13">FACILITIES</option>
<option value="7">INSTANT MESSAGING</option>
<option value="8">MOBILE COLLABORATION</option>
<option value="141">Network Address Translation</option>
<option value="15">NETWORKING</option>
<option value="3">SECURITY</option>
<option value="16">STORAGE</option>
<option value="81">TestTechnology_Dont_Delete</option>
<option value="10">UNIFIED COMMUNICATIONS</option>
<option value="20">VCH VIDEO</option>
<option value="17">VIRTUALIZATION And CONSOLIDATION</option>
<option value="21">VtechnologyVtechnologyVtechnologyVtechnology</option>
<option value="2">WIRELESS</option>
<option class=" firepath-matching-node" value="142">Cloud Service Assurance</option>
<option value="123">Cloud Service Assurance Zenoss for Data Center and Cloud</option>
<option value="6">CUSTOMER COLLABORATION</option>
<option value="12">DESKTOP VIRTUALIZATION</option>
<option value="13">FACILITIES</option>
<option value="7">INSTANT MESSAGING</option>
<option value="8">MOBILE COLLABORATION</option>
<option value="141">Network Address Translation</option>
<option value="15">NETWORKING</option>
<option value="3">SECURITY</option>
<option value="16">STORAGE</option>
<option value="81">TestTechnology_Dont_Delete</option>
<option value="10">UNIFIED COMMUNICATIONS</option>
<option value="20">VCH VIDEO</option>
<option value="17">VIRTUALIZATION And CONSOLIDATION</option>
<option value="21">VtechnologyVtechnologyVtechnologyVtechnology</option>
<option value="2">WIRELESS</option>
</select>
</td>
I am not a Java person, so forgive me, but you are essentially just wanting to loop through all the options from that Select, keep a record of them, and ensure that one each loop iteration, that option doesn't already exist, so pseudo-code:
Select selectElement = new Select(driver.findElement(By.xpath(//*[#id='unmappedTech'])));
ArrayList<string> options = new ArrayList<string>();
for (WebElement element in selectElement.getOptions()) {
if (options.contains(element.getText())) {
// do something that lets the test fail because the option is listed twice
}
options.add(element.getText());
}
This isn't a Selenium problem as such, it's just comparing a list to see if something is already contained within that list.
This is the java code. Essentially checking whether duplicate is found by rechecking a set.
List<WebElement> options = driver.findElement(
By.xpath("//*[#id='unmappedTech']")).findElements(
By.tagName("option"));
HashSet<String> optionNames = new HashSet<>();
for (WebElement option : options) {
if (optionNames.contains(option.getText()))
System.out.println("Duplicate found");
else
optionNames.add(option.getText());
}
Select s = new Select(driver.findElement(
By.xpath("//Select[#id='unmappedTech']")));
List<WebElement> list = s.getOptions();
Set<String> listNames = new HashSet<String>(list.size());
for (WebElement element : list) {
//Set will not allow to add duplicate value
if(listNames.add(element.getText())==false){
System.out.println("Duplicate value is: "+element.getText());
}
}

Categories