Pressing Ctrl + A in Selenium WebDriver - ruby

Is there a way to press the Ctrl + A keys using Selenium WebDriver?
I checked the Selenium libraries and found that Selenium allows key press of special and function keys only.

One more solution (in Java, because you didn't tell us your language - but it works the same way in all languages with Keys class):
String selectAll = Keys.chord(Keys.CONTROL, "a");
driver.findElement(By.whatever("anything")).sendKeys(selectAll);
You can use this to select the whole text in an <input>, or on the whole page (just find the html element and send this to it).
For using Selenium Ruby bindings:
There's no chord() method in the Keys class in Ruby bindings. Therefore, as suggested by Hari Reddy, you'll have to use Selenium Advanced user interactions API, see ActionBuilder:
driver.action.key_down(:control)
.send_keys("a")
.key_up(:control)
.perform

To click Ctrl+A, you can do it with Actions
Actions action = new Actions();
action.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0061')).perform();
\u0061 represents the character 'a'
\u0041 represents the character 'A'
To press other characters refer the unicode character table - http://unicode.org/charts/PDF/U0000.pdf

In Selenium for C#, sending Keys.Control simply toggles the Control key's state: if it's up, then it becomes down; if it's down, then it becomes up. So to simulate pressing Control+A, send Keys.Control twice, once before sending "a" and then after.
For example, if we is an input IWebElement, the following statement will select all of its contents:
we.SendKeys(Keys.Control + "a" + Keys.Control);

You could try this:
driver.findElement(By.xpath(id("anything")).sendKeys(Keys.CONTROL + "a");

Since Ctrl+A maps to ASCII code value 1 (Ctrl+B to 2, up to, Ctrl+Z to 26).
Try:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Remote;
namespace SeleniumHqTest
{
class Test
{
IWebDriver driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("http://localhost");
IWebElement el = driver.FindElement(By.Id("an_element_id"));
char c = '\u0001'; // ASCII code 1 for Ctrl-A
el.SendKeys(Convert.ToString(c));
driver.Quit();
}
}

For Python:
ActionChains(driver).key_down(Keys.CONTROL).send_keys("a").key_up(Keys.CONTROL).perform();

The simplest answer in C# (if you are C# inclined).
Actions action = new Actions();
action.KeyDown(OpenQA.Selenium.Keys.Control).SendKeys("a").KeyUp(OpenQA.Selenium.Keys.Control).perform();
This answer is almost given by Hari Reddy, but I have fixed the case which he'd got wrong on some keywords, added the KeyUp or you get in a mess leaving the control key down.
I've also added the clarification on OpenQA.Selenium.Keys, because you may also be using Windows.Forms on the same class as I was an require this clarity.
Lastly, I type "a" because I found that to be the simplest way and I can see no suggestion from the OP that they don't want the simplest answer.
Many thanks to Hari Reddy though as I was a novice in Actions class usage and I was writing many different commands. Chaining them together the way he showed is quicker :-)

WebDriver driver = new FirefoxDriver();
Actions action = new Actions(driver);
action.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
This method removes the extra call ( String.ValueOf() ) to convert unicode to string.

It works for me:
OpenQA.Selenium.Interactions.Actions action
= new OpenQA.Selenium.Interactions.Actions(browser);
action.KeyDown(OpenQA.Selenium.Keys.Control)
.SendKeys("a").KeyUp(OpenQA.Selenium.Keys.Control).Perform();

Actions act = new Actions(driver);
act.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).build().perform();

I found that in Ruby, you can pass two arguments to send_keys
Like this:
element.send_keys(:control, 'A')

This is what worked for me using C# (Visual Studio 2015) with Selenium:
new Actions(driver).SendKeys(Keys.Control + "A").Perform();
You can add as many keys as wanted using (+) in between.

Java
The Robot class will work much more efficiently than sending the keys through Selenium sendkeys. Please try:
Example:
Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_A);
To use the above Robot class, you need to import java.awt.Robot;'.

By using the Robot class in Java:
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class Test1
{
public static void main(String[] args) throws Exception
{
WebDriver d1 = new FirefoxDriver();
d1.navigate().to("https://www.youtube.com/");
Thread.sleep(3000);
Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_TAB);
rb.keyRelease(KeyEvent.VK_TAB);
rb.keyPress(KeyEvent.VK_TAB);
rb.keyRelease(KeyEvent.VK_TAB);
// Perform [Ctrl+A] Operation - it works
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_A);
// It needs to release key after pressing
rb.keyRelease(KeyEvent.VK_A);
rb.keyRelease(KeyEvent.VK_CONTROL);
Thread.sleep(3000);
}
}

Below code worked for me.
WebElement textbox = driver.findElement(By.id("username"));
textbox.sendKeys("Testing");
textbox.sendKeys(Keys.CONTROL+"A");

Related

How do pagination in JavaScript when use WebDriver Sampler?

1.I used Webdriver sampler and write selenium -Javascript.
In Java we use" List obj= driver.findElements(By.xpath("//span[starts-with(text(),'REQ_')]")); " In java script what we use for listing?
2.In my application total 50 pages are present. and every page has 10 items are present. Now I want to click the first button then click the next button and so on..up to the button is disabled.
How is this achieved?
3.How elementToBeClickable() method is used in javascript?
4.How isEnabled() method is used in javascript?
5.and also WebDriverWait() is not worked for below example
var pkg = JavaImporter(org.openqa.selenium)
var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait)
var conditions = org.openqa.selenium.support.ui.ExpectedConditions
var wait=new support_ui.WebDriverWait(WDS.browser, 5000)
WDS.sampleResult.sampleStart()
WDS.browser.get('http://example.com')
wait.until(conditions.presenceOfElementLocated(pkg.By.linkText('More finformation...')))
var element=WDS.browser.findElement(pkg.By.linkText("More information..."))
element.click()
WDS.sampleResult.sampleEnd()
It return error-->
javax.script.ScriptException: TypeError: Can not create new object with constructor org.openqa.selenium.support.ui.WebDriverWait with the passed arguments; they do not match any of its method signatures. in <eval> at line number 4 atjdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:47
6.can you please provide full documentation for javascript syntax and all methods used for scripting used in WebDriver sampler.
The same, var obj = WDS.browser.findElements(org.openqa.selenium.By.xpath("//span[starts-with(text(),'REQ_')]"));
Take a look at while statement
The same
var wait = new org.openqa.selenium.support.ui.WebDriverWait(WDS.browser, 25)
wait.until(org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable(org.openqa.selenium.By.xpath("//your-selector-here")))
The same
var element = WDS.browser.findElement(org.openqa.selenium.By.xpath("//span[starts-with(text(),'REQ_')]")
var enabled = element.isEnabled()
Look for the JavaDoc for the version you're using, it might be the case that the API has changed
The "full" documentation available at Using Java from Scripts guide, some useful examples can be found in The WebDriver Sampler: Your Top 10 Questions Answered
Don't you want to try Groovy instead of JavaScript?

MS Bot Framework: Is there a way to cancel a prompt dialog? [duplicate]

The PromptDialog.Choice in the Bot Framework display the choice list which is working well. However, I would like to have an option to cancel/escape/exit the dialog with giving cancel/escape/exit optioin in the list. Is there anything in PromptDialog.Choice which can be overridden since i have not found any cancel option.
here is my code in c#..
PromptDialog.Choice(
context: context,
resume: ChoiceSelectAsync,
options: getSoftwareList(softwareItem),
prompt: "We have the following software items matching " + softwareItem + ". (1), (2), (3). Which one do you want?:",
retry: "I didn't understand. Please try again.",
promptStyle: PromptStyle.PerLine);
Example:
Bot: We have the following software items matching Photoshop. (1), (2), (3). Which one do you want
Version 1
Version 2
Version 3
What I want if user enter none of above or a command or number, cancel, exit, that bypasses the options above, without triggering the retry error message.
How do we do that?
There are two ways of achieving this:
Add cancel as an option as suggested. While this would definitely work, long term you will find repeating yourself a lot, plus that you will see the cancel option in the list of choices, what may not be desired.
A better approach would be to extend the current PromptChoice to add your exit/cancelation logic. The good news is that there is something already implemented that you could use as is or as the base to achieve your needs. Take a look to the CancelablePromptChoice included in the BotBuilder-Samples repository. Here is how to use it.
Just add the option "cancel" on the list and use a switch-case on the method that gets the user input, then call your main manu, or whatever you want to do on cancel
Current Prompt Choice does not work in that way to allows user select by number. I have override the ScoreMatch function in CancleablePromptChoice as below
public override Tuple<bool, int> ScoreMatch(T option, string input)
{
var trimmed = input.Trim();
var text = option.ToString();
// custom logic to allow users to select by number
int isInt;
if(int.TryParse(input,out isInt) && isInt <= promptOptions.Options.Count())
{
text = promptOptions.Options.ElementAt(isInt - 1).ToString();
trimmed = option.ToString().Equals(text) ? text :trimmed;
}
bool occurs = text.IndexOf(trimmed, StringComparison.CurrentCultureIgnoreCase) >= 0;
bool equals = text == trimmed;
return occurs ? Tuple.Create(equals, trimmed.Length) : null;
}
#Ezequiel Once again thank you!.

Selecting several elements from a grid using while loop and xpath in Selenium webDriver

I have a while loop containing an Xpath expression. How can I have the while loop working properly with only the value of tr[index] changing within the Xpath? Below is an example:
//this is what I currently have:
while(webDriver.findElement(By.xpath("//*[#id='sharing_list']/tbody/tr[1]/td[4]")).isDisplayed())
{
webDriver.findElement(By.xpath("//*[#id='sharing_list']/tbody/tr[1]/td[4]/span")).click();
}
//and this is what I would like to have:
int n=1;
while(webDriver.findElement(By.xpath("//*[#id='sharing_list']/tbody/tr[n]/td[4]")).isDisplayed())
{
webDriver.findElement(By.xpath("//*[#id='sharing_list']/tbody/tr[n]/td[4]/span")).click();
n++;
}
Does any one have an idea how to make it work? I am using Selenium 2.33.
Your help will be very appreciated.
This is really a String issue. Replace your tr[n] with tr["+n+"]

How can I check if some text exist or not in the page using Selenium?

I'm using Selenium WebDriver, how can I check if some text exist or not in the page? Maybe someone recommend me useful resources where I can read about it. Thanks
With XPath, it's not that hard. Simply search for all elements containing the given text:
List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + text + "')]"));
Assert.assertTrue("Text not found!", list.size() > 0);
The official documentation is not very supportive with tasks like this, but it is the basic tool nonetheless.
The JavaDocs are greater, but it takes some time to get through everything useful and unuseful.
To learn XPath, just follow the internet. The spec is also a surprisingly good read.
EDIT:
Or, if you don't want your Implicit Wait to make the above code wait for the text to appear, you can do something in the way of this:
String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains(text));
This will help you to check whether required text is there in webpage or not.
driver.getPageSource().contains("Text which you looking for");
You could retrieve the body text of the whole page like this:
bodyText = self.driver.find_element_by_tag_name('body').text
then use an assert to check it like this:
self.assertTrue("the text you want to check for" in bodyText)
Of course, you can be specific and retrieve a specific DOM element's text and then check that instead of retrieving the whole page.
There is no verifyTextPresent in Selenium 2 webdriver, so you've to check for the text within the page source. See some practical examples below.
Python
In Python driver you can write the following function:
def is_text_present(self, text):
return str(text) in self.driver.page_source
then use it as:
try: self.is_text_present("Some text.")
except AssertionError as e: self.verificationErrors.append(str(e))
To use regular expression, try:
def is_regex_text_present(self, text = "(?i)Example|Lorem|ipsum"):
self.assertRegex(self.driver.page_source, text)
return True
See: FooTest.py file for full example.
Or check below few other alternatives:
self.assertRegexpMatches(self.driver.find_element_by_xpath("html/body/div[1]/div[2]/div/div[1]/label").text, r"^[\s\S]*Weather[\s\S]*$")
assert "Weather" in self.driver.find_element_by_css_selector("div.classname1.classname2>div.clearfix>label").text
Source: Another way to check (assert) if text exists using Selenium Python
Java
In Java the following function:
public void verifyTextPresent(String value)
{
driver.PageSource.Contains(value);
}
and the usage would be:
try
{
Assert.IsTrue(verifyTextPresent("Selenium Wiki"));
Console.WriteLine("Selenium Wiki test is present on the home page");
}
catch (Exception)
{
Console.WriteLine("Selenium Wiki test is not present on the home page");
}
Source: Using verifyTextPresent in Selenium 2 Webdriver
Behat
For Behat, you can use Mink extension. It has the following methods defined in MinkContext.php:
/**
* Checks, that page doesn't contain text matching specified pattern
* Example: Then I should see text matching "Bruce Wayne, the vigilante"
* Example: And I should not see "Bruce Wayne, the vigilante"
*
* #Then /^(?:|I )should not see text matching (?P<pattern>"(?:[^"]|\\")*")$/
*/
public function assertPageNotMatchesText($pattern)
{
$this->assertSession()->pageTextNotMatches($this->fixStepArgument($pattern));
}
/**
* Checks, that HTML response contains specified string
* Example: Then the response should contain "Batman is the hero Gotham deserves."
* Example: And the response should contain "Batman is the hero Gotham deserves."
*
* #Then /^the response should contain "(?P<text>(?:[^"]|\\")*)"$/
*/
public function assertResponseContains($text)
{
$this->assertSession()->responseContains($this->fixStepArgument($text));
}
In c# this code will help you to check whether required text is there in webpage or not.
Assert.IsTrue(driver.PageSource.Contains("Type your text here"));
You can check for text in your page source as follow:
Assert.IsTrue(driver.PageSource.Contains("Your Text Here"))
In python, you can simply check as follow:
# on your `setUp` definition.
from selenium import webdriver
self.selenium = webdriver.Firefox()
self.assertTrue('your text' in self.selenium.page_source)
Python:
driver.get(url)
content=driver.page_source
if content.find("text_to_search"):
print("text is present in the webpage")
Download the html page and use find()
boolean Error = driver.getPageSource().contains("Your username or password was incorrect.");
if (Error == true)
{
System.out.print("Login unsuccessful");
}
else
{
System.out.print("Login successful");
}
JUnit+Webdriver
assertEquals(driver.findElement(By.xpath("//this/is/the/xpath/location/where/the/text/sits".getText(),"insert the text you're expecting to see here");
If in the event your expected text doesn't match the xpath text, webdriver will tell you what the actual text was vs what you were expecting.
string_website.py
search string in webpage
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
browser.get("https://www.python.org/")
content=browser.page_source
result = content.find('integrate systems')
print ("Substring found at index:", result )
if (result != -1):
print("Webpage OK")
else: print("Webpage NOT OK")
#print(content)
browser.close()
run
python test_website.py
Substring found at index: 26722
Webpage OK
d:\tools>python test_website.py
Substring found at index: -1 ; -1 means nothing found
Webpage NOT OK
You can check a source code if the text exists:
source_code = driver.page_source
if "Im not a Robot" not in source_code:

Selecting Ajax Dropdown suggestion list using Selenium for Firefox

How can i select Ajax Dropdown suggestion list item using selenium code for firefox??
My problem is :the Ajax dropdown list is visible but it is not selected and next steps gets stuck.
May be selenium is waiting for something.
the list that page populates is dynamic and in bla bla tags.
Please help with a example code.
How can i use waitfor* here.
Remember i am not using firefox ide but i am writing a code.
Please help.
I had a similar problem whereby, selenium was able to find the dropdown menu but was unable to click on the visible text. I later found out that there was an Ajax call that was populating the dropdown menu data and as a result selenium seemed to not be able to select the intended visible text because the list items had not been fully populated. That is, by the time the script was selecting my option value, Ajax had not completely loaded the menu options. Here's my solution:
public void nameOfCollegeList(String optionItem) {
// declare the dropdownMenu web element
WebElement dropDownMenu = driver.findElement(By.cssSelector("#CollegeNames"));
// click on the dropdownMenu element to initiate Ajax call
dropDownMenu.click();
// keep checking the drop down menu item list until you find the desired text that indicates that the menu has
// been fully loaded. In this example I always expect "Other (please specify)" to be the last item in the drop down menu.
// If I don't find the expected last item in the list in my if condition, execute the else condition by calling the
// same method(recursively). Please note that if the "if" statement is never satisfied then you'll end up with an
// infinite loop.
if (dropDownMenu.getText().contains("Other (please specify)")) {
new Select(dropDownMenu).selectByVisibleText(optionItem);
}
else {
nameOfCollegeList(optionItem);
}
}
i am little confused with your question at " :the Ajax dropdown list is visible but it is not selected "
this sounds like that the element is disabled. (Java coding)
if so selenium.isElementDisabled()
if not then,
1) programming laguage solution using while loop and isElementPresent() OR isElementDisabled()
//trigger the Ajax request and then
long initialTime = System.currentTimeMillis();
do{
thread.sleep(1000);
}while((!selenium.isElementPresent("AjaxElement")) && (System.getCurrentTimeMillis() - initialTime <= 5000)) ;
//some thing like above for client programming solution...but for,
2) selenium's inbuilt solution
we have a method called waitForCondition("java script to be executed", "time out value");
this method loops the javascript statement until it returns true or the supplied time out occurs
here the important thing is analyzing the application/Ajax element to find out which particular condition of the element changes.
from your explation my guess is this, display=none will be changed to display=block OR
disabled=true will be changed to disabled=false OR isReadOnly will be changed to no such attribute ect.....(you need to figure out this)
and then, use this attribute = value to build a javascript function as ,
selenium.waitForCondition("window.document.getElementById('AJAX ELEMENT').disabled == 'false'", "3000");
you can work out the above statement however you want in your programming language.
try {
//do the action which triggers the Ajax call
selenium.waitForCondition("window.document.getElementById('AJAX ELEMENT[drop down element]').disabled == 'false'", "3000");
//OR
selenium.waitForCondition("window.document.getElementById('AJAX ELEMENT').disabled == 'false'", "3000");
}
catch(SeleniumException se)
{
if((se.getMessage()).toLowerCase().contains("timed out")
throw //..some a custom exception however your organisation requires
}
selenium.select("drop down element id", "option id");
and so on.....

Resources