How to set text in textarea quickly using Java and Selenium - java

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')");

Related

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 get visible text from some paragraph by using javascript executor and web driver

In a site I have:
<p id="tempid" value="Manual Effect">testing the test</p>
String value = (String)((JavascriptExecutor) this).executeScript("return window.document.getElementById('tempid').value");
System.out.println("value is : " + value);
I am getting null value or nothing.
I want to get the test "testing the test" as output.
Like everyone already mentioned. Don't use Javascript. If you do, you don't need WebDriver.
WebElement para = driver.findElement(By.id("tempid"));
String text = para.getText(); //this will return "testing the test"
String value = para.getAttribute("value"); //this will return "Manual Effect"
Sir,
You try this solution...
String script = "return document.getElementByTagName('p').tempid.getInnerHtml()";
String script1 = "return document.getElementById('tempid').innerHTML;
JavaScriptExecutor js = (JavaScriptExecutor)driver;
String value = (String)js.executeScript(script);
System.out.println(value);
JavascriptExecutor is more better than webdriver ant many assepect.
WebDriver are work on the basis of webElements, some time if webElement is not accessible. It Show staleElementException, ElementNotFoundException..., Its some time headache.
But JavaScript Executor work directly On HTML. So that why its better...
(String) ((JavascriptExecutor) this)
.executeScript("return window.document.getElementById('tempid').innerHTML");

Ajax and selenium working intermittently

I am trying to use the following code from http://www.thoughtworks-studios.com/twist/2.3/help/how_do_i_handle_ajax_in_selenium2.html:
String xpathExpr = "//div[#id='contentPane']/div[#class='g-x-Aa ud-Aa']/div[#class='Nj mu']/div[#class='ez vcard']/div[#class='l-Gy Vra']/div[#class='qga']/div[#class='g-Ua-z9']/div[#class='WAa']/div[#class='Yia']/div[#class='twa Vxa']/div[#class='zD us']/div[#class='hx a-f-e']";
//String xpathExpr = "//div[#id='contentPane']/div[#class='g-x-Aa ud-Aa']";
By by = By.xpath(xpathExpr);
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement elem1 = wait.until(visibilityOfElementLocated(by));
System.out.println(Util.getInnerHtml(driver, elem1));
public static String getInnerHtml(WebDriver driver, WebElement element) {
return (String)((JavascriptExecutor)driver).executeScript("return arguments[0].innerHTML;", element);
}
To test some ajax page. The weird thing is that it works the first time but never works after that. Besides the DOM element is loaded in firefox and is clearly visible yet, the program is stuck at the innerhtml part and sometimes wait.until part.
Any idea how to debug and troubleshoot this problem?
Thanks
Ok problem solved. The problem with the CSS class name in xpath I think.

webdriver target="_blank"

Page has image with hyperlink and that hyperlink has target="_blank" and every time i press that image loads new firefox and that hyperlink is redirected to that new firefox web
and i lose all control of that webpage.
Is possilble to remove or change that target="_blank" on hyperlink, bcause i want to load webpage in same webdriver
WebDriver driver = new FirefoxDriver();
driver.get("http://www.page.eu/");
WebElement submit;
submit = driver.findElement(By.xpath("//img[#alt='page']"));
submit.click();
that hyperlink have target="_blank"
i need to change that target somehow by using webdriver + javascript maybe or what?
is it possible?
edited
thanks for suggestions, but still is this problem
i tried to make like Grooveek said but no changes
WebElement labels2 = driver.findElement(By.xpath("//a[#href='http://tahtpage.net']"));
WebElement aa = (WebElement) ((JavascriptExecutor) driver).executeScript("labels2.setAttribute('target','_self')",labels2 );
aa.click();
i have an error
org.openqa.selenium.WebDriverException: null (WARNING: The server did not provide any stacktrace information)
i'm not good at javascrit so i think is problem in that executor
Instead of clicking on the image, you could just directly go to the URL in the link:
WebElement link = (driver.findElement(By.xpath("//img[#alt='page']/parent::*"));
String href = link.getAttribute("href");
driver.get(href);
Try the following:
WebElement labels2 = driver.findElement(By.xpath("//a[#href='http://tahtpage.net']"));
WebElement aa = (WebElement) ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('target','_self')",labels2 );
aa.click();
You are getting a null exception because you are using labels2 in your javascript, which doesn't exist in that context. By changing it to arguments[0] Selenium will take the labels2 parameter and reference it in javascript appropriately.
Evaluating javascript in the window will help you to suppress target=blank links
Here's the example from the Webdriver docs
List<WebElement> labels = driver.findElements(By.tagName("label"));
List<WebElement> inputs = (List<WebElement>) ((JavascriptExecutor)driver).executeScript(
"var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +
"inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels);
Adapt it to modify the DOM to throw target="_blank links"
Why don't you wanna use SwitchTo().Window?
I think you should use the SwitchTo().Window as suggested by simeon sinichkin. however, i didn't like his example.Here is simple example.
driver.Navigate().GoToUrl(baseURL);
//Get the Main Window Handle
var baseWindow = driver.CurrentWindowHandle;
// navigate to another window (_blank)
driver.FindElement(By.Id("btn_help")).Click();
Thread.Sleep(2000);
//switch back to Main Window
driver.SwitchTo().Window(baseWindow);
hope that helps
Why don't you use:
target="_self"

Categories