Monday, October 30, 2017

Unable to select Bootstrap dropdown in Java Selenium

Leave a Comment

I'm having a very difficult time selecting bootstrap dropdown in Selenium.

I'm new to Selenium so any suggestion and guidance would be very helpful, as what I'd love to do is just select the dropdown, type "email", and press enter during the instance.

I've gone through dozens of solutions, but none of them have worked for this specific issue.

What can I do? Please help.

Salenium

package newPackage;      import org.openqa.selenium.By;  import org.openqa.selenium.WebDriver;  import org.openqa.selenium.WebElement;  import org.openqa.selenium.chrome.ChromeDriver;  import org.openqa.selenium.interactions.Actions;      public class importLeads {    	public static void main(String args[]) throws Exception {  		  		        System.setProperty("webdriver.chrome.driver", "C:\\Users\\David\\Downloads\\Notes\\WebDriver\\chromedriver.exe");      WebDriver driver = new ChromeDriver();        //login to site      driver.get("https://demos5.softaculous.com/Mautic/s/contacts/import/new");      driver.manage().window().maximize();      driver.findElement(By.id("username")).sendKeys("admin");      driver.findElement(By.id("password")).sendKeys("password");      driver.findElement(By.className("btn")).click();      Thread.sleep(2000);        //importing Data      WebElement uploadBox = driver.findElement(By.id("lead_import_file"));      uploadBox.sendKeys("C:\\Users\\David\\Downloads\\data_file.csv");      driver.findElement(By.id("lead_import_start")).click();        //Select from dropdown      WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_address')"));      Actions cursor = new Actions(driver);      cursor.moveToElement(dropdownToggle);      cursor.click();      cursor.perform();      Thread.sleep(1000);      WebElement weh = driver.findElement(By.id("lead_field_import_email_address_chosen"));        Actions cursor2 = new Actions(driver);      cursor2.moveToElement(weh);      cursor2.click();    	}  }


Here is the link to the data file ufile.io/vy2ws

In order for the upload of the .CSV file to work, you must be running a local version of this software. Download can be found here: https://www.mautic.org/m/asset/54:mautic-2100

Once uploaded, it should look like this where it asks to choose from the drop-down.

enter image description here

HTML

<div class="col-sm-4">     <div class="row">        <div class="form-group col-xs-12 ">           <label class="control-label" for="lead_field_import_email_address">Email address</label>                   <div class="choice-wrapper">              <select id="lead_field_import_email_address" name="lead_field_import[email_address]" class="form-control" autocomplete="false" style="display: none;">                 <option value=""></option>                 <optgroup label="Contact">                    <option value="email">Email</option>                 </optgroup>              </select>              <div class="chosen-container chosen-container-single chosen-with-drop chosen-container-active" style="width: 100%;" title="" id="lead_field_import_email_address_chosen">                 <a class="chosen-single chosen-default">                    <span>Choose one...</span>                    <div><b></b></div>                 </a>                 <div class="chosen-drop">                    <div class="chosen-search"><input type="text" autocomplete="off"></div>                    <ul class="chosen-results">                       <li class="group-result">Contact</li>                       <li class="active-result group-option" data-option-array-index="9" style="">Email</li>                    </ul>                 </div>              </div>           </div>        </div>     </div>  </div>


Replacing :

WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_add‌​ress')"));  

to this :

WebElement dropdownToggle = driver.findElement(By.id("lead_field_import_email_address"))‌​; 

resulted in:

Starting ChromeDriver 2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f) on port 35535 Only local connections are allowed. Oct 22, 2017 1:20:49 AM org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Detected dialect: OSS Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"lead_field_import_email_address"}   (Session info: chrome=61.0.3163.100)   (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 0 milliseconds For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z' System info: host: 'DAVID-PC', ip: '192.235.0.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_151' Driver info: org.openqa.selenium.chrome.ChromeDriver Capabilities [{mobileEmulationEnabled=false, hasTouchScreen=false, platform=XP, acceptSslCerts=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=XP, setWindowRect=true, unexpectedAlertBehaviour=, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\David\AppData\Local\Temp\scoped_dir4068_28713}, takesHeapSnapshot=true, pageLoadStrategy=normal, unhandledPromptBehavior=, databaseEnabled=false, handlesAlerts=true, version=61.0.3163.100, browserConnectionEnabled=false, nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}] Session ID: ee90469095e7b1121dc2e387d8e485e6 *** Element info: {Using=id, value=lead_field_import_email_address}     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)     at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)     at java.lang.reflect.Constructor.newInstance(Unknown Source)     at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)     at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)     at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)     at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:82)     at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:45)     at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)     at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)     at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)     at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:356)     at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:402)     at org.openqa.selenium.By$ById.findElement(By.java:218)     at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:348)     at newPackage.importLeads.main(importLeads.java:31) 

Replacing

WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_address')"));     Actions cursor = new Actions(driver); 

with

WebElement element =  driver.findElement(By.id("lead_field_import_email_address"));     Select select = new Select(element); 

resulted in:

Starting ChromeDriver 2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f) on port 32443 Only local connections are allowed. Oct 23, 2017 1:36:09 PM org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Detected dialect: OSS Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"lead_field_import_email_address"}   (Session info: chrome=61.0.3163.100)   (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 0 milliseconds For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z' System info: host: 'HOME-PC', ip: '192.235.0.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_151' Driver info: org.openqa.selenium.chrome.ChromeDriver Capabilities [{mobileEmulationEnabled=false, hasTouchScreen=false, platform=XP, acceptSslCerts=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=XP, setWindowRect=true, unexpectedAlertBehaviour=, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\David\AppData\Local\Temp\1\scoped_dir5416_25737}, takesHeapSnapshot=true, pageLoadStrategy=normal, unhandledPromptBehavior=, databaseEnabled=false, handlesAlerts=true, version=61.0.3163.100, browserConnectionEnabled=false, nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}] Session ID: 40cde314a5a76400aceff8b625b38e3c *** Element info: {Using=id, value=lead_field_import_email_address}     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)     at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)     at java.lang.reflect.Constructor.newInstance(Unknown Source)     at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)     at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)     at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)     at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:82)     at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:45)     at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)     at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)     at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)     at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:356)     at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:402)     at org.openqa.selenium.By$ById.findElement(By.java:218)     at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:348)     at newAutomation.importLeads.main(importLeads.java:33) 

2 Answers

Answers 1

I tried to replicate manually the steps of your code but when I load the data_file.csv and I click the Upload button:

enter image description here

nothing happens.

And, in the html, there isn't the element that you try to find:

WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_address')")); 

That's why I wrote this comment.

I can imagine that should open something. From the informations:

  • Limit
  • Delimiter
  • Enclosure
  • Escape

I can suppose that you have to upload a file with a particular format.

EDIT

Trying locally it works. I don't understand well this part of your code:

        //Select from dropdown         WebElement dropdownToggle = driver.findElement(By.xpath("id('lead_field_import_email_address')"));         Actions cursor = new Actions(driver);         cursor.moveToElement(dropdownToggle);         cursor.click();         cursor.perform();         Thread.sleep(1000);         WebElement weh = driver.findElement(By.id("lead_field_import_email_address_chosen"));          Actions cursor2 = new Actions(driver);         cursor2.moveToElement(weh);         cursor2.click(); 

If you want to choose from the email drop-down, you could use the xpath:

WebElement we = driver.findElement(By.xpath("//div[@class='choice-wrapper']//div[@id='lead_field_import_email_address_chosen']")); 

or simply the id:

WebElement we= driver.findElement(By.id("lead_field_import_email_address_chosen")); 

and execute the interested operation.

So, for example:

    WebElement we= driver.findElement(By.id("lead_field_import_email_address_chosen"));     we.click();     we.sendKeys("email");     we.sendKeys(Keys.ENTER); 

EDIT 2

Your problem is that you use Thread.sleep(XXXX); in order to wait the elements. This is not deterministic. You must use an explicit wait.

From Explicit Waits:

An explicit wait is a code you define to wait for a certain condition to occur before proceeding further in the code. The extreme case of this is time.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

So, in java you need:

WebDriverWait wait = new WebDriverWait(driver, 15); WebElement we=wait.until(ExpectedConditions.elementToBeClickable(By.id("lead_field_import_email_address_chosen"))); 

Always from the previous link:

This waits up to 15 seconds before throwing a TimeoutException unless it finds the element to return within 15 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. A successful return is for ExpectedCondition type is Boolean return true or not null return value for all other ExpectedCondition types.

Finally, the entire code:

        String geckoDriver = System.getProperty("pathTo/geckodriver";         System.setProperty("webdriver.gecko.driver", geckoDriver);         WebDriver driver= new FirefoxDriver();         driver.get("http://localhost:8888/2.10.0/s/contacts/import/new");         driver.findElement(By.id("username")).sendKeys("admin");         driver.findElement(By.id("password")).sendKeys("password");         driver.findElement(By.className("btn")).click();          WebDriverWait wait = new WebDriverWait(driver, 15);          WebElement uploadBox=wait.until(ExpectedConditions.elementToBeClickable(By.id("lead_import_file")));         uploadBox.sendKeys("/pathTo/data_file.csv");         driver.findElement(By.id("lead_import_start")).click();          //Select from dropdown         WebElement we=wait.until(ExpectedConditions.elementToBeClickable(By.id("lead_field_import_email_address_chosen")));         we.click();         we.sendKeys("email");         we.sendKeys(Keys.ENTER); 

EDIT 3

With Firefox, the above code (in my tests) is ok. I noticed that you use Chrome. With Chrome, I have this problem. The solution works for me:

        //Select from dropdown         WebElement we=wait.until(ExpectedConditions.elementToBeClickable(By.id("lead_field_import_email_address_chosen")));         /*we.click();         we.sendKeys("email");*/          Actions actions = new Actions(driver);         actions.moveToElement(we);         actions.click();         actions.sendKeys("email");         actions.sendKeys(Keys.ENTER);         actions.build().perform(); 

Answers 2

Looking at the HTML you have provided, the WebElement with id="lead_field_import_email_address" is with in a Select tag. So instead of using Actions Class in this case we should try to use the Select Class instead as follows:

WebElement element =  driver.findElement(By.id("lead_field_import_email_address")); Select select = new Select(element); 

Next, we can select any of the options by invoking either selectByIndex(n), selectByValue("value") or selectByVisibleText("visible_text") method.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment