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);
}
Related
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();
This code work but sendKeys send all char one by one and is it very very long time (40s).
String value = "...very long text...";
WebElement element = ...
element.sendKeys(value);
How to set text in textarea quickly using Java and Selenium? either with an element of Selenium or by modifying the speed or the characters are sent one by one temorary.
Please no solution with javascript execution.
The sendKeys method is the only pure Java way to enter text into a text field using Selenium. Unfortunately all other ways require JavaScript, which is something you do not want to do.
Your only other alternative is to contribute to the Selenium project on GitHub by submitting a pull request with the desired behavior, and convince the World Wide Web Consortium to include this new method (sendKeysQuickly?) in the official WebDriver spec: https://www.w3.org/TR/webdriver/ — not a small task indeed!
Here's a way to use the clipboard for this:
String value = "...very long text...";
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable transferable = new StringSelection(value);
clipboard.setContents(transferable, null);
wait = new WebDriverWait(driver, ec_Timeout);
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.name("name_of_input_element")));
String vKey = "v";
try
{
element.sendKeys(Keys.CONTROL , vKey);
}
catch (Exception ex)
{
}
/!\ Caution, is it a workaround only.
String value = "...very long text...";
WebElement element = ...
String javascript = "arguments[0].value=arguments[1];";
(JavascriptExecutor) driver.executeScript(javascript, element, value.substring(0, value.length() - 1));
element.sendKeys(value.substring(value.length() - 1));
/!\ 2nd workaround (not work on remote):
String value = "...very long text...";
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(value), null);
WebElement element = ...
element.sendKeys(Keys.CONTROL , "v");
you can set the value directly using js script:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('textareaId').setAttribute('value', 'yourText')");
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
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");
I am working on a public site:
http://preview.harriscountyfws.org/
I am trying to do something simple:
Select an option from a dropdown.
The very same code that works on IE and Chrome, fails on Firefox. No error is generated. It just doesn't pick the right option ("Channel Status") from the Site Type Dropdown.
Any help on this appreciated!
WebElement listbox_element2, we2;
String ariaOwns = "siteType_listbox";
String searchText2 = "Channel Status";
listbox_element2 = driver.findElement(By.cssSelector("span[aria-owns='" + ariaOwns + "']"));
listbox_element2.click();
Sleep(2000);
we2 = driver.findElement(By.xpath("//li[text()='" + searchText2 + "']"));
if (we2 != null) {
we2.click();
}`
You might want to introduce an explicit wait while running test on firefox browser and then print all the drop down options as part of debugging. By making a use of selectByValue(value) method, you can select an item from drop list.
WebElement mySelectElement = driver.findElement(By.id("mySelect"));
Select dropdown= new Select(mySelectElement);
List options = dropdown.getOptions();
for (WebElement option : options) {
System.out.println(option.getText()); //output "option1", "option2", "option3"
}