I am having difficulty selecting options from a dropdown list using Selenium Webdriver. Below is the HTML snippet:
<span id="id14">
<div class="stadium-input-row">
<span class="inputContainer">
<select id="id1f" class="departurePoint stadiumSelect" onchange="var wcall=..........">
<option value="">Please select</option>
<option value="BHX"> Birmingham - (BHX) </option>
<option value="GLA"> Glasgow - (GLA) </option>
<option value="LON"> London - (LON) </option>
<option value="MAN"> Manchester - (MAN) </option>............
The select tag id changes each time the DOM is loaded.
The select tag is greyed out until it is interacted with.
My code
Select oSelect = new Select(driver.findElement(By.xpath("(.//select)[1]"));
oSelect.selectByVisibleText("Birmingham");
Error
org.openqa.selenium.NoSuchElementException: Cannot locate element
with text: Birmingham
In debugging mode, the dropdown does not seem to be activated (clicked) by the driver.
There's a weird (at least it's weird to me) thing going on on that site. The SELECT that you are trying to access is permanently hidden (which means it can't be interacted with using Selenium). Users interact with DIVs, etc. via a fake dropdown (it's not a SELECT) and the result of those selections are stored in the hidden SELECT. There are two ways to accomplish your task.
Deal with what you can see.
This is really a pain on this site. I think it can be ultimately done but I don't want to spend any more time on it myself so I'll show you the door and you'll have to pick up where I left off. The code below will open the departure dropdown. From there, you find the departure airport and click on it. Done. Harder than it sounds...
driver.findElement(By.cssSelector("div.custom-select.departurePoint.airportSelect")).click();
Cheat and use JavascriptExecutor.
NOTE: By doing this you are no longer executing a real user scenario since users can't click on hidden elements or inject Javascript commands into the page. As long as you are OK with this, here's a sample.
This code executes Javascript on the page using the JavascriptExecutor. You pass the function a string you are looking for in the options, e.g. you can pass "EMA" or "East Midlands - (EMA)" or anywhere inbetween. The JS code will grab the hidden SELECT, search through the OPTIONS, and select the first that matches.
Also note: You will not see the UI update with the selection. Once you click SEARCH, it will work. I have tried it myself and it works.
Yet another note: I use Eclipse as my editor so the // #formatter:off you see in the code below keeps Eclipse from wrapping/reformatting the extra long string that contains the JS code. You can leave or remove it as you like. I like it there because I can still read the JS code with it formatted and indented like it is and I don't want Eclipse messing it up.
selectOption("EMA");
public void selectOption(String option)
{
// #formatter:off
String script =
"function selectOption(s) {\r\n" +
" var sel = document.querySelector('select.departurePoint.airportSelect');\r\n" +
" for (var i = 0; i < sel.options.length; i++)\r\n" +
" {\r\n" +
" if (sel.options[i].text.indexOf(s) > -1)\r\n" +
" {\r\n" +
" sel.options[i].selected = true;\r\n" +
" break;\r\n" +
" }\r\n" +
" }\r\n" +
"}\r\n" +
"return selectOption('" + option + "');";
// #formatter:on
((JavascriptExecutor) driver).executeScript(script);
}
what you need to do:
List<WebElement> options = driver.findElement(By.xpath("//div[#class='stadium-input-row']//select")).findElements(By.tagName("option"));
that will create you list of option tags as WebElement objects
or
Select oSelect = new Select(driver.findElement(By.xpath("//div[#class='stadium-input-row']//select"));
or just take the select as WebElement object
WebElement selectElement = driver.findElement(By.xpath("//div[#class='stadium-input-row']//select"));
Hovering element
Actions action = new Actions(driver);
WebElement hoverElement = driver.findElement(By.xpath("//div[#class='stadium-input-row']//select"));
action.moveToElement(hoverElement);
action.click().build().perform();
As your exception clearly says Cannot locate element with text: Birmingham means it compares with whole visible text option so you should try as below :-
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement select = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(.//select)[1]")));
Select oSelect = new Select(select);
oSelect.selectByVisibleText("Birmingham - (BHX)");
or
oSelect.selectByIndex(1);
or
oSelect.selectByValue("BHX");
Edited :- If unfortunately none of the above solution works you should try using JavascriptExecutor as below :-
((JavascriptExecutor)driver).executeScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text.indexOf(arguments[1]) != -1){ select.options[i].selected = true; } }",
driver.findElement(By.xpath("(.//select)[1]")),
"Birmingham");
Hope it will help you..:)
Select will not work in all the situations. Try this code
List <WebElement> options = driver.findElements(By.xpath("Target Element with Options"));
String element;
for(int i=0;i<options.size();i++)
{
element = options[i].get(i).getAttribute("value");
if(element.equals("BHX")){
options.get(i).click();
}
}
Related
I was trying to search and add product in the cart using selenium but was not able to successfully do it
driver.get("https://www.bigbasket.com/cl/fruits-vegetables/?nc=nb");
List<WebElement> product = driver.findElements(By.xpath("//div[#qa=\'product\']"));
System.out.println("prdoduct=" + product.size());
for(int i=0;i<product.size();i++)
{
String name = product.get(i).getText();
System.out.println("NAME is" + name);
String xp= "(//button[#qa=\'add\'])" + "["+i+ "]";
System.out.println("xp="+xp);
if(name.contains("Cauliflower"))
{
System.out.println("xp" +xp);
driver.findElement(By.xpath(xp)).click();
}
}
In this previous product is getting selected but when I was debugging it was on the cauliflower but still the previous product is getting selected
there is a chance that some time the element get overlapped by another element. At this time, the normal selenium click will try to click on the overlapped element. so it is better to use js click, it will click the exact element even if it is overlapped
WebElement element= driver.findElement(By.xpath(xp));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);
There is also a chance for issue in your xpath. Since list starts at 0 , you may need to change i in to i+1 in xp for getting current selection add button.do try this xpath too
String xp= "(//button[#qa=\'add\'])" + "["+(i+1)+ "]";
Induce WebDriverWait() and wait for visibilityOfAllElementsLocatedBy() and use following css selector and xpath.
driver.get("https://www.bigbasket.com/cl/fruits-vegetables/?nc=nb");
List<WebElement> product =new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div[qa='product_name']>a")));
System.out.println("prdoduct=" + product.size());
for(int i=0;i<product.size();i++)
{
String name = product.get(i).getText();
System.out.println("NAME is" + name);
if(name.contains("Cauliflower"))
{
driver.findElement(By.xpath("//div[#qa='product_name']//a[text()='" + name + "']/following::button[1]")).click();
}
}
<div id="address" class="guideFieldDescription short" style="null;display:none">
<p>
Enter home address for the contact person. Leave blank if you don't have one. Home Address and Mailing Address must be located in the United States. No international addresses will be accepted. If the home addresses and mailing addresses are different, you must fill out both sections.<br>
</p>
I'm trying to get the tag content but I'm getting either null or empty using the script below
WebElement WebElement = driver.findElement(By.xpath("//*[#id='address']"));
List<WebElement> paras = WebElement.findElements(By.tagName("p"));
System.out.println("Size = " + paras.size() + " " + paras.toString() );
for (WebElement para : paras) {
System.out.println(para.getText());}
I get the size is = 1, but the getText() return empty.
Selenium getText() can't get text from elements with display: none, which includes the div and its children p paragraphs. If the elements were visible (weren't set to display: none;), your code would be working.
Instead of using getText(), you can use a JavascriptExecutor to get the innerText of the element if it's invisible. See this possible duplicate question: Using selenium, can I get the text of an invisible element?
Here is a function which gets the inner text
/**
* Get the innerText from an element.
* #param driver the WebDriver
* #param element the element to get innerText from
* #return the element's innerText
*/
public static String getInnerText(WebDriver driver, WebElement element) {
JavascriptExecutor executor = (JavascriptExecutor) driver;
return (String) executor.executeScript("return arguments[0].innerText", element);
}
This function is used in the below code sample.
To see the difference between getText() and getting innerText for visible and invisible elements, here is a complete working example program (NOTE the step in the middle to debug and add the display: none manually):
import io.github.bonigarcia.wdm.WebDriverManager;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
class DemonstrateGetTextVsGetInnerTextForDisplayNoneElements {
public static void main(final String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
// Let's go to a page that mirrors the use case of a div container,
// with children paragraphs.
// The difference: this page doesn't have display: none set on the container.
driver.get("https://www.google.com/intl/en/about/");
final WebElement container = driver.findElement(By.className("home-hero-copy"));
final List<WebElement> paragraphs = container.findElements(By.tagName("p"));
System.out.println("getText() works as normal for *VISIBLE* containers and paragraphs.");
System.out.println("CONTAINER: " + container.getText());
System.out.println(
"LIST OF PARAGRAPHS, Size = " + paragraphs.size() + " " + paragraphs.toString());
for (final WebElement paragraph : paragraphs) {
System.out.println("PARAGRAPH: " + paragraph.getText());
}
System.out.println("SET THE JAVA DEBUGGER TO PAUSE RIGHT HERE, "
+ "GO INTO THE BROWSER AND INJECT \"display: none;\" "
+ "as a style on the div.home-hero-copy element to make"
+ "the div and its child paragraphs invisible. "
+ "You can do this by using the developer tools elements panel.");
System.out.println("If you've made the container invisible, "
+ "you should notice that in the following block of printouts "
+ "that we've still got references to the WebElements (they aren't stale) "
+ "but when we try to getText() while they are invisible from 'display: none;', "
+ "we won't get any text back.");
System.out.println("CONTAINER: " + container.getText());
System.out.println(
"LIST OF PARAGRAPHS, Size = " + paragraphs.size() + " " + paragraphs.toString());
for (final WebElement paragraph : paragraphs) {
System.out.println("PARAGRAPH: " + paragraph.getText());
}
System.out.println("Now, let's try getting the text via 'innerText' with a Javascript Executor");
System.out.println("CONTAINER: " + getInnerText(driver, container));
System.out.println(
"LIST OF PARAGRAPHS, Size = " + paragraphs.size() + " " + paragraphs.toString());
for (final WebElement paragraph : paragraphs) {
System.out.println("PARAGRAPH: " + getInnerText(driver, paragraph));
}
System.out.println("As you can see, getting inner text works when the element is invisible!");
driver.quit();
}
/**
* Get the innerText from an element.
* #param driver the WebDriver
* #param element the element to get innerText from
* #return the element's innerText
*/
public static String getInnerText(WebDriver driver, WebElement element) {
JavascriptExecutor executor = (JavascriptExecutor) driver;
return (String) executor.executeScript("return arguments[0].innerText", element);
}
}
The output of this program should look like this
Connected to the target VM, address: '127.0.0.1:62943', transport: 'socket'
Starting ChromeDriver 71.0.3578.33 (269aa0e3f0db08097f0fe231c7e6be200b6939f7) on port 15369
Only local connections are allowed.
Nov 13, 2018 11:07:46 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
getText() works as normal for *VISIBLE* containers and paragraphs.
CONTAINER: Our mission is to organize the world’s information and make it universally accessible and useful.
LIST OF PARAGRAPHS, Size = 1 [[[[[ChromeDriver: chrome on MAC (bbb9840f94250510047ac8e04b055d88)] -> class name: home-hero-copy]] -> tag name: p]]
PARAGRAPH: Our mission is to organize the world’s information and make it universally accessible and useful.
SET THE JAVA DEBUGGER TO PAUSE RIGHT HERE, GO INTO THE BROWSER AND INJECT "display: none;" as a style on the div.home-hero-copy element to makethe div and its child paragraphs invisible. You can do this by using the developer tools elements panel.
If you've made the container invisible, you should notice that in the following block of printouts that we've still got references to the WebElements (they aren't stale) but when we try to getText() while they are invisible from 'display: none;', we won't get any text back.
CONTAINER:
LIST OF PARAGRAPHS, Size = 1 [[[[[ChromeDriver: chrome on MAC (bbb9840f94250510047ac8e04b055d88)] -> class name: home-hero-copy]] -> tag name: p]]
PARAGRAPH:
Now, let's try getting the text via 'innerText' with a Javascript Executor
CONTAINER: Our mission is to organize the world’s information and make it universally accessible and useful.
LIST OF PARAGRAPHS, Size = 1 [[[[[ChromeDriver: chrome on MAC (bbb9840f94250510047ac8e04b055d88)] -> class name: home-hero-copy]] -> tag name: p]]
PARAGRAPH: Our mission is to organize the world’s information and make it universally accessible and useful.
As you can see, getting inner text works when the element is invisible!
Disconnected from the target VM, address: '127.0.0.1:62943', transport: 'socket'
Process finished with exit code 0
And just in case Google ever changes their page, here is what the div and its children look like:
<div class="home-hero-copy center">
<p>Our mission is to <span class="color-hero">organize</span> the world’s <span class="color-hero">information</span> and make it <span class="color-hero">universally accessible</span> and <span class="color-hero">useful</span>.</p>
</div>
How to display all the values in auto drop down list using selenium web driver when it is developed using <div> tag.
My code
driver.get("https://www.yatra.com/");// URl of yatra
String origin ="(//input[#name='flight_origin_city'])[1]";// text box for entering origin
driver.findElement(By.xpath(origin)).sendKeys("Bangalore");
String destination = "(//input[#name='flight_destination_city'])[1]";// text for entering destination
driver.findElement(By.xpath(destination)).sendKeys("M");
List<WebElement> lists= driver.findElements(By.xpath("(//div[#class='viewport'])[2]")); // this is the div where all the values are present.
for (int i=0; i<lists.size();++i){
System.out.println(lists.get(i).getText());// getting the text for all the values.
}
The xpath "(//div[#class='viewport'])[2]" gives you a single element, not list. This is also not where the options are stored, its the parent of the container where they are stored. Try
List<WebElement> lists= driver.findElements(By.xpath("(//div[#class='overview'])[3]//li"));
Your case is a bit difficult, but that's what makes it worth exploring. Here's a step wise dissection of the problem:
Desktop notification dialog
First of all, when I tried to run your test in Chrome, the "Do you want to allow Desktop notifications?" dialog interfered with the test (it popped up some time after the second sendKeys which is why the text box lost its focus and one of the entries got accepted which made it impossible to find the other suggestions).
I worked around that using this tip: Disable Chrome notifications (Selenium)
Finding the right container
You got pretty far already by identifying that you can locate the container of the suggestions as By.xpath("(//div[#class='viewport'])[2]"). From there though, you need to look more specifically for the right child elements. Also as this is dynamic content, it is advisable to use an explicit wait statement to make sure the test doesn't fail prematurely in case the element takes longer to load.
I changed your test so that it would look the <li> elements which are children of the <div> elements with the viewport class. Those elements have children which format the city, airport and country names accordingly. To get the text of those, you have to drill down a bit more into the DOM structure. Here's the solution for that:
WebElement list = new WebDriverWait(driver, 2000).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//div[#class='viewport'])[2]")));
List<WebElement> elements = list.findElements(By.tagName("li"));
for (WebElement element : elements) {
String city = element.findElement(By.className("ac_cityname")).getText();
String airport = element.findElement(By.className("ac_airportname")).getText();
String country = element.findElement(By.className("ac_country")).getText();
System.out.println(city + " " + airport + " (" + country + ")");
}
So far, so good. But note that this solution gives you the followiing output:
Mumbai (BOM) Chatrapati Shivaji (India)
Madras (MAA) Chennai (India)
Chennai (MAA) Chennai (India)
Madurai (IXM) (India)
()
()
()
()
()
()
Scrolling
This is because of another speciality of your page: It only renders the text for the elements that are actually in view. So in addition to the code above, apply this trick to make sure all elements are being scrolled to before retrieving their text: Scroll Element into View with Selenium
Long story short: Here's my final version:
driver.get("https://www.yatra.com/");// URl of yatra
String origin ="(//input[#name='flight_origin_city'])[1]";// text box for entering origin
driver.findElement(By.xpath(origin)).sendKeys("Bangalore");
String destination = "(//input[#name='flight_destination_city'])[1]";// text for entering destination
driver.findElement(By.xpath(destination)).sendKeys("M");
WebElement list = new WebDriverWait(driver, 2000).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//div[#class='viewport'])[2]")));
List<WebElement> elements = list.findElements(By.tagName("li"));
for (WebElement element : elements) {
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
String city = element.findElement(By.className("ac_cityname")).getText();
String airport = element.findElement(By.className("ac_airportname")).getText();
String country = element.findElement(By.className("ac_country")).getText();
System.out.println(city + " " + airport + " (" + country + ")");
}
That should give you the following output when running in Google Chrome:
Mumbai (BOM) Chatrapati Shivaji (India)
Madras (MAA) Chennai (India)
Chennai (MAA) Chennai (India)
Madurai (IXM) Madurai (India)
Mangalore (IXE) Bajpe (India)
Mysore (MYQ) Mysore (India)
Coorg (MYQ) (nearest airport Mysore) (India)
Male (MLE) Male (Maldives)
Melbourne (MEL) Tullamarine (Australia)
Mauritius (MRU) Plaisancet (Mauritius)
My Companys website is compatible only with IE. So i cannot use IDE for recording webdriver scripts.
There are HTML pages which has about 100 or 200(not exact count) of textboxes and Dropdowns.
Writing java code to automate this is very much tedious.
Can someone provide me with tool or utility to read the HTML file itself and generate the corresponding code ?
Or guide me how to develop a utility to meet my need ?
For example :
Consider an html file like this
<html>
<body>
<input name = "employee_name" />
<select id = "designation">
<option value = "MD">MD</option>
<option value = "programmer"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
<body>
</html>
If i give this file as input to utility it will generate me a java file like this
WebDriver driver = new InternetExplorerDriver();
WebElement employee_name = driver.findElement(By.name("employee_name"));
employee_name.sendKeys("...");
Select designation = new Select(driver.findElement(By.id("designation")));
designation.selectByVisibleText("...");
Thanks in Advance !
You should be using "Selenium Builder" rather than "Selenium IDE", BUT, in theory, you could get all similar elements from a page in a group like so:
List<WebElement> bodyinputs = driver
.findElements( By.xpath("//div[#class='body']/input") );
List<WebElement> footeranchors = driver
.findElements( By.xpath("//div[#class='footer']/a") );
Then, for each of these groups, you can loop through the lists and use a JavaScriptExecutor to evaluate and figure out the XPath for each element and store the XPath in a hashtable with each Element:
protected String getXPath() {
String jscript = "function getPathTo(node) {" +
" var stack = [];" +
" while(node.parentNode !== null) {" +
" stack.unshift(node.tagName);" +
" node = node.parentNode;" +
" }" +
" return stack.join('/');" +
"}" +
"return getPathTo(arguments[0]);";
return (String) driver.executeScript(jscript, webElement);
}
Then, the final step, you can auto-generate "By locators" using the HashTable as input.
But even if you do that you still need to write code to intelligently figure out which By locators get which inputs and which ones don't.
I'm trying to use Selenium WebDriver to input text to a GWT input element that has default text, "Enter User ID". Here are a few ways I've tried to get this to work:
searchField.click();
if(!searchField.getAttribute("value").isEmpty()) {
// clear field, if not already empty
searchField.clear();
}
if(!searchField.getAttribute("value").isEmpty()) {
// if it still didn't clear, click away and click back
externalLinksHeader.click();
searchField.click();
}
searchField.sendKeys(username);
The strange thing is the above this only works some of the time. Sometimes, it ends up searching for "Enter User IDus", basically beginning to type "username" after the default text -- and not even finishing that.
Any other better, more reliable ways to clear out default text from a GWT element?
Edited to add: The HTML of the input element. Unfortunately, there's not much to see, thanks to the JS/GWT hotness. Here's the field when it's unselected:
<input type="text" class="gwt-TextBox empty" maxlength="40">
After I've clicked it and given it focus manually, the default text and the "empty" class are removed.
The JS to setDefaultText() gets called both onBlur() and onChange() if the change results in an empty text field. Guess that's why the searchField.clear() isn't helping.
I've also stepped through this method in debug mode, and in that case, it never works. When run normally, it works the majority of the time. I can't say why, though.
Okay, the script obviously kicks in when the clear() method clears the input and leaves it empty. The solutions it came up with are given below.
The naïve one, presses Backspace 10 times:
String b = Keys.BACK_SPACE.toString();
searchField.sendKeys(b+b+b+b+b+b+b+b+b+b + username);
(StringUtils.repeat() from Apache Commons Lang or Google Guava's Strings.repeat() may come in handy)
The nicer one using Ctrl+A, Delete:
String del = Keys.chord(Keys.CONTROL, "a") + Keys.DELETE;
searchField.sendKeys(del + username);
Deleting the content of the input via JavaScript:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].value = '';", searchField);
searchField.sendKeys(username);
Setting the value of the input via JavaScript altogether:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].value = '" + username + "';", searchField);
Note that javascript might not always work, as shown here: Why can't I clear an input field with javascript?
For what it is worth I'm have a very similar issue. WebDriver 2.28.0 and FireFox 18.0.1
I'm also using GWT but can reproduce it with simple HTML/JS:
<html>
<body>
<div>
<h3>Box one</h3>
<input id="boxOne" type="text" onfocus="if (this.value == 'foo') this.value = '';" onblur="if (this.value == '') this.value = 'foo';"/>
</div>
<div>
<h3>Box two</h3>
<input id="boxTwo" type="text" />
</div>
</body>
</html>
This test fails most of the time:
#Test
public void testTextFocusBlurDirect() throws Exception {
FirefoxDriver driver = new FirefoxDriver();
driver.navigate().to(getClass().getResource("/TestTextFocusBlur.html"));
for (int i = 0; i < 200; i++) {
String magic = "test" + System.currentTimeMillis();
driver.findElementById("boxOne").clear();
Thread.sleep(100);
driver.findElementById("boxOne").sendKeys(magic);
Thread.sleep(100);
driver.findElementById("boxTwo").clear();
Thread.sleep(100);
driver.findElementById("boxTwo").sendKeys("" + i);
Thread.sleep(100);
assertEquals(magic, driver.findElementById("boxOne").getAttribute("value"));
}
driver.quit();
}
It could just be the OS taking focus away from the browser in a way WebDriver can't control. We don't seem to get this issue on the CI server to maybe that is the case.
I cannot add a comment yet, so I am putting it as an answer here. I want to inform you that if you want to use only javascript to clear and/or edit an input text field, then the javascript approach given by #slanec will not work. Here is an example: Why can't I clear an input field with javascript?
In case you use c# then solution would be :
// provide some text
webElement.SendKeys("aa");
// this is how you use this in C# , VS
String b = Keys.Backspace.ToString();
// then provide back space few times
webElement.SendKeys(b + b + b + b + b + b + b + b + b + b);