Select options from Autopopulate text boxes using Selenium webdriver - java

Driver.findElement(By.xpath("//*[#id='client']")).sendKeys("Ho");
Driver.manage().timeouts().implicitlyWait(1,TimeUnit.MINUTES);
WebElement dropdown = (new WebDriverWait(Driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id='client']")));
Driver.findElement(By.xpath("//*[#id='collapseClientInfo']/div/form/div[3]/div[2]/ul/li[1]/a")).sendKeys(Keys.ENTER);
Could you please help me to select auto populate value from drop down list:
We've Client textbox which is an auto-populate box.
When I enter "ho" text in the client field, it shows me the drop down which has values related to my entered text i.e. ho, then I have to select those values which are available under list.
In above code I've tried with Press Enter but unable to select the value.
Could you please check the above code and help me out for the same?

You should try as below :-
WebDriverWait wait = new WebDriverWait(Driver, 60);
//wait until loader invisible
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("loaderDiv")));
//this sleep is required because after invisibility of loader focus goes to first input which is Requisition Number
//If you are filling form from first input no need to for this sleep
//if you want to input directly to client field need to sleep to avoid focus first
Thread.sleep(3000);
//Now find the client input and set value
WebElement client = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("client")));
client.sendKeys("Ho");
//Now find all the showing option
List<WebElement> dropdownOptions = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.cssSelector("ul.dropdown-menu a")));
//Now select the first option
dropdownOptions.get(0).click();

Below approach might be helpful:
// Enter text in auto complete text box
driver.findElement(By.xpath("//*[#id='client']")).sendKeys("Ho");
// Wait for options to display
Thread.sleep(5000);
// Option to select
String optionToSelect = "Honda";
Boolean isOptionSelected = Boolean.FALSE;
// Get the options displayed
List<WebElement> options = driver.findElements(By
.cssSelector("ul.dropdown-menu a"));
// Select option
for (WebElement webElement : options) {
if (webElement.getText().equalsIgnoreCase(optionToSelect)) {
webElement.click();
isOptionSelected = Boolean.TRUE;
}
}
if (isOptionSelected) {
// Option is selected
} else {
// Expected option is not displayed. Fail the script
}

Try this:
Select drpCountry = new Select(driver.findElement(By.id("searchOptions")));
drpCountry.selectByVisibleText("By author");

Related

How to click button and delete input text with Selenium WebDriver

I'm able to navigate this page [here][1] and enter this website [here][2](TOKEN CREATED FOR EACH DEMO FOR THIS LINK)
I'm also able to extract the value from the round count using this xpath here #class,'coefficient'
I can locate the input element on the left hand side but only one text value is deleted. I want to delete all values and enter 50.
It also seems like I can locate the left hand side button because I'm not getting any exceptions or errors but the button is not clickable.
The below two lines:
firstInput.sendKeys(Keys.CONTROL + "a");
firstInput.sendKeys(Keys.DELETE);
is basically to clear the input field, since .clear() is not working as expected in this case, we'd have to do CTRL+a and then delete
A full code will look like this:
driver.manage().window().maximize();
driver.get("https://www.spribe.co/games/aviator");
WebDriverWait wait = new WebDriverWait(driver, 30);
try {
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),' Got it')]"))).click();
}
catch(Exception e){
e.printStackTrace();
}
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'Play Demo ')]"))).click();
String originalWinHandle = driver.getWindowHandle();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Yes')]"))).click();
List<String> allHandles = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(allHandles.get(1));
WebElement firstInput = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[text()='BET']/ancestor::div[contains(#class,'feature')]/descendant::input")));
firstInput.sendKeys(Keys.CONTROL + "a");
firstInput.sendKeys(Keys.DELETE);
firstInput.sendKeys("20");
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//label[text()='BET']/.."))).click();

Automate/handle 5th dropdown url https://jedwatson.github.io/react-select/ named as Github users(Aysnc with fetch.js)

I have problem to automate this drop down using selenium web driver using Java
This is the link - Go to 5th drop down named as Github users (fetch. js)
I am not able to enter the data into search field.
I am using send keys after perform click but it throws an exception like this " element is not interact able"
Steps I follow
driver.findElement(By.xpath("xapth")).click
drop down opens with no options because it is searchable and options are coming dynamically after entering key word into the search field.
driver.findElement(By.xpath("xapth")).sendkeys("Test");
Sendkeys are not working in this case because of drop down closed when perform send keys action.
<div class="Select-placeholder">Select...</div>
Below is the code which is working.
Please do optimize the code by removing thread.Sleep and putting some meaningful waits as per your requirement.
driver.Navigate().GoToUrl("https://jedwatson.github.io/react-select/");
IWebElement element1 = driver.FindElement(By.XPath("//span[#id='react-select-6--value']"));
IWebElement element2 = driver.FindElement(By.XPath("//span[#id='react-select-6--value']/div[2]/input[1]")) ;
element1.Click();
Thread.Sleep(2000);
element2.SendKeys("Test");
Thread.Sleep(1000);
element2.SendKeys(Keys.Tab);
Please note that element2 gets activated once you click on element1.
Try the following code:
public void typeAndSelect() {
WebElement searchBox = driver.findElement(By.xpath("//div[#class='section'][5]//div[#class='Select-control']"));
searchBox.click();
WebElement inputField = driver.findElement(By.xpath("//div[#class='section'][5]//input[#role='combobox']"));
inputField.clear();
String searchWord = "test";
inputField.sendKeys(searchWord);
WebElement selectDropdown = driver.findElement(By.xpath("//div[#class='Select-menu-outer']//div[#role='option'][text()='" + searchWord +"']"));
// wait for search results.
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(selectDropdown)).click();
}
Correct the following xpath part
"//div[#class='section'][5]"
to your implementation of the dropdown

Inserting values into a text fields using automation - Selenium

I have logged into a website page using automation code (Selenium) but now there are fields in which data needs to be entered
But how to do this using Selenium?
How to write the code for it?
Use sendKeys method.
driver.findElement(By.id("InputBox_ID")).sendKeys("Test data");
Use following lines of code to insert value into text.
WebElement Element1 = driver.findElementByName("abc");
Element1.sendKeys("value that you want to enter.");
When searching for a field to fill in, right click on its element in the web page and click "Inspect Element". The ID should be highlighted in the popup menu, and that is going to be the ID You specify into the "By.xpath()" Method from seleniums API.
Here is an example on how to fill in fields for Gmail.
System.setProperty("webdriver.gecko.driver", "/path/to/geckodriver");
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new FirefoxDriver();
driver.get(Links.Register_Gmail);
driver.findElement(By.xpath("//*[#id='FirstName']")).sendKeys(firstname);
driver.findElement(By.xpath("//*[#id='LastName']")).sendKeys(lastname);
driver.findElement(By.xpath("//*[#id='GmailAddress']")).sendKeys(username);
driver.findElement(By.xpath("//*[#id='Passwd']")).sendKeys(password);
driver.findElement(By.xpath("//*[#id='PasswdAgain']")).sendKeys(password);
driver.findElement(By.xpath("//*[#id='BirthMonth']")).click();
driver.findElement(By.xpath("//*[#id=':" + random(1, 9) + "']")).click();
driver.findElement(By.xpath("//*[#id='BirthDay']")).sendKeys("" + random(1, 27));
driver.findElement(By.xpath("//*[#id='BirthYear']")).sendKeys("" + random(1950, 1990));
driver.findElement(By.xpath("//*[#id='Gender']")).click();
driver.findElement(By.xpath("//*[#id=':f']")).click();
driver.findElement(By.xpath("//*[#id='submitbutton']")).click();
driver.findElement(By.xpath("//*[#id='tos-scroll-button']")).click();
driver.findElement(By.xpath("//*[#id='tos-scroll-button']")).click();
driver.findElement(By.xpath("//*[#id='tos-scroll-button']")).click();
driver.findElement(By.xpath("//*[#id='iagreebutton']")).click();
you can do it simply by just right click on the field that you want to fill and click inspect, if you are using firefox then it is quiet simple by using firepath but if you are using chrome then simply right click on the field, click on inspect element and find a unique id of that field and put it inside these below lines
driver.findelement(By.id("")).sendelement(""),
you can use different field than id if you find something else unique.
You can use the below method and call it wherever you want to enter text
public static void enterTextInput(WebElement element, String value) throws InterruptedException{
String val = value;
element.clear();
Thread.sleep(1000);
for (int i = 0; i < val.length(); i++){
char c = val.charAt(i);
String str = new StringBuilder().append(c).toString();
element.sendKeys(str);
}
Thread.sleep(1500);
}

Not able to extract password field in a modal window using CSS selector - Selenium Java

I am able to click on sign in link in the start page [a link] http://imgur.com , resulting modal window of username and password field. while I was trying to extract password field on the resulted page, found no elements of username and password fields. Even I checked the source code at that instant using driver.getPageSource(); and there is no sign of username or password elements. Following is the code used to extract password field from the specified URL.
pwd = driver.findElement(By.cssSelector("input[type='password']"));
code for clicking the modal window is
driver.findElement(By.partialLinkText("sign in")).click();
Later I found that they are using iframes so I started searching the password fields in each iframe as shown below.
List<WebElement> iFrames = null;
WebElement iFramePwd=null;
iFrames = driver.findElements(By.tagName("iframe"));
if (iFrames.size() > 0) {
for (int l = 0; l < iFrames.size(); l++) {
try{ driver.switchTo().frame(l);
}
catch(NoSuchFrameException ljn){
System.out.println(ljn);
driver.switchTo().defaultContent();
continue;
}
try {
try{
iFramePwd = driver.findElement(By.cssSelector("input[type='password']"));
}
catch(NoSuchElementException lkn){
System.out.println(lkn);
driver.switchTo().defaultContent();
continue;
}
Size of iframes displaying as 5 but when i try to switch to the iFrame iam always getting NoSuchFrameException.
Please visit the specified URL for analyzing the source code. I dont know where i am missing the point. Is there any way to get password field from the modal window. Any help would be greatly appreciated. Thanks in advance
Try this code
WebDriver driver = new FirefoxDriver();
driver.get("http://imgur.com/");
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.findElement(By.partialLinkText("sign in")).click();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.className("cboxIframe")));
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("f")));
driver.findElement(By.name("username")).sendKeys("abcd");
driver.findElement(By.xpath(".//*[#id='password']/input")).sendKeys("abcd");
driver.close();
driver.quit();
If we use loop to reach the iframe, there is a problem. You don't know which ifrmae you are in because List of web elements does not grantee the exact sequence of iframe in page. For Example below code is not working and showing error "Element belongs to a different frame than the current one - switch to its containing frame to use it"
List<WebElement> my_iframes = driver.findElements(By.tagName("iframe"));
// moving to inner iframe
if(my_iframes.size() > 0){
for(WebElement my_iframe : my_iframes){
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(my_iframe));
}
}
driver.findElement(By.name("username")).sendKeys("abcd");
driver.findElement(By.xpath(".//*[#id='password']/input")).sendKeys("abcd");

Select DropDown option using selenium

If someone could help me with this mystery.. Here is the url
Here if you can see the Date of Birth Fields I am able to select the Month and Date but I am not able to select Year
I Tried selecting Using Value, Index it did not work the same code worked for Month and Date
Below is My Code:
WebElement W = driver.findElement(By.xpath("//html/body/form[#id='aspnetForm'][contains(#action,'ActivateAccount.aspx?key=')][#method='post'][#name='aspnetForm']/div[#class='border4']/div[#id='page']/div[#class='IE-SCroll-mid']/div/div[#class='change-info-contain']/div/div/div/label[3]/select"));
Select dropdown = new Select(W);
dropdown.selectByValue("1997");
Try implementing explicit wait with that. That will make sure the elemenet is present before start looking for that.
By byId = By.id("ctl00_mcp_ddlYear");
//use explicit wait to make sure the element is there
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(byId));
Select dropdown = new Select(myDynamicElement);
dropdown.selectByValue("1997");
You can also use the cssSelector directly wait for the specific option to be present with the following code
//explicit wait
By byCss = By.cssSelector("#ctl00_mcp_ddlYear>option[value='1997']");
WebElement element = new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(byCss));
element.click();

Categories