Press TAB and then ENTER key in Selenium WebDriver - selenium-webdriver

Press TAB and then ENTER key in Selenium WebDriver
GenericKeywords.typein(class.variable, PageLength);
pagelength is nothing but string.
After this code, I have to give Tab key. I don't know how to give Tab key in Selenium WebDriver?

Using Java:
WebElement webElement = driver.findElement(By.xpath(""));//You can use xpath, ID or name whatever you like
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);

In javascript (node.js) this works for me:
describe('UI', function() {
describe('gets results from Bing', function() {
this.timeout(10000);
it('makes a search', function(done) {
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
driver.get('http://bing.com');
var input = driver.findElement(webdriver.By.name('q'));
input.sendKeys('something');
input.sendKeys(webdriver.Key.ENTER);
driver.wait(function() {
driver.findElement(webdriver.By.className('sb_count')).
getText().
then(function(result) {
console.log('result: ', result);
done();
});
}, 8000);
});
});
});
For tab use webdriver.Key.TAB

Using Java:
private WebDriver driver = new FirefoxDriver();
WebElement element = driver.findElement(By.id("<ElementID>"));//Enter ID for the element. You can use Name, xpath, cssSelector whatever you like
element.sendKeys(Keys.TAB);
element.sendKeys(Keys.ENTER);
Using C#:
private IWebDriver driver = new FirefoxDriver();
IWebElement element = driver.FindElement(By.Name("q"));
element.SendKeys(Keys.Tab);
element.SendKeys(Keys.Enter);

In python this work for me
self.set_your_value = "your value"
def your_method_name(self):
self.driver.find_element_by_name(self.set_your_value).send_keys(Keys.TAB)`

Be sure to include the Key in the imports...
const {Builder, By, logging, until, Key} = require('selenium-webdriver');
searchInput.sendKeys(Key.ENTER) worked great for me

Sometimes Tab will not move forward, you can use with combination of Tab and Enter keys as below
Using C# :
Driver.SwitchTo().Window(Driver.WindowHandles[1]);
IWebElement element = Driver.FindElement(By.TagName("body"));
element.SendKeys(Keys.Tab + Keys.Enter);
Driver.SwitchTo().Window(Driver.WindowHandles[0]);

WebElement webElement = driver.findElement(By.xpath(""));
//Enter the xpath or ID.
webElement.sendKeys("");
//Input the string to pass.
webElement.sendKeys(Keys.TAB);
//This will enter the string which you want to pass and will press "Tab" button .

Related

Why does Selenium sometimes skip checkboxes?

I'm having troubles regarding webdriver not being able to click checkboxes sometime and just skipping them, both in Firefox and Chrome.
I've tried different solutions such as
click();
action.moveToElement(checkbox).clickAndHold(checkbox).release().perform();
jse.javascriptExecutor(argument[0].click(),checkbox).
Here I provide the Javascript code I have for the click event
...
var selectCorrectOption = function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
$(this).find('> input').prop('checked', false);
} else {
$(this).addClass('selected');
$(this).find('> input').prop('checked', true);
}
};
$('.option > .input-container').on('click', selectCorrectOption);
...
the HTML code where it is attached the javascript click event
<div class="input-container selected" data-choice-id="2">
<input type="radio">
</div>
the Java code data uses a data-attribute to access the element is question. Notice also that once the div is clicked, a 'selected' class appears(which is the current state) on the code below.
WebDriverWait wait = new WebDriverWait(driver, 20);
JavascriptExecutor jse = (JavascriptExecutor)driver;
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[data-choice-id='"+ wrongOptionVal +"']")));
radio=wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("[data-choice-id='"+ wrongOptionVal +"']")));
jse.executeScript("arguments[0].scrollIntoView()", radio);
jse.executeScript("arguments[0].click()", radio);
I expected it to be consistent ,most of the times work, but there are always that one or two times it fails.
I do not know why this happens, I do however know how this can be addressed. You can implement a FluentWait with polling mechanism, which will do three things:
locate the element,
select the radio box,
return getAttribute("class").contains("selected") value.
If getAttribute("class").contains("selected") will result in false the process should repeat.
FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
.pollingEvery(Duration.ofMillis(300))
.withTimeout(Duration.ofSeconds(10));
fluentWait.until(new Function<WebDriver, Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
WebElement element = driver.findElement(By.cssSelector(radioCssSelector));
element.click();
return element.getAttribute("class").contains("selected");
}
});

Click link under navigation bar in Selenium Webdriver

I am trying to click the link under the navigation bar. I tried driver.findelement in this code snippet. It selects the link but the click event is not taking place.
WebElement menu=driver.findElement(By.xpath(".//*[#id='bs-example-navbar-collapse-1']"));
//WebElement menu = driver.findElement(By.XPATH("Coplete_navigationbar_xpath")); List<WebElement>
List<WebElement> allLinks = menu.findElements(By.tagName("a"));
String MenuOptn="";
for (WebElement w : allLinks)
{
MenuOptn=w.getText();
if(MenuOptn.equalsIgnoreCase("TRACKING"))
{
// System.out.println("tracking");
w.click();
System.out.println("tracking");
break;
}
System.out.print(w.getText());
}
Try click using javascript
WebElement element = webDriver.findElement(locator);
JavascriptExecutor executor = (JavascriptExecutor) webDriver;
executor.executeScript("arguments[0].click();", element);
Try below options:
driver.FindElement(By.Xpath("//a[contains(., '<link_text>')]")).click();
or
new Actions(driver).moveToElement(driver.FindElement(By.Xpath("//a[contains(., '<link_text>')]")),10,10).doubleClick().perform();
I hope it will be helpful

How to focus on second tab and work on it using selenium webdriver

I have opened the link now i am clicking on login link on that page,
By clicking on login button its opening in a new tab automatically. I have to fill the form in that tab. For that i tried following code:
Actions act = new Actions(Initialsetupfirefox.driver);
new Actions(Initialsetupfirefox.driver) .keyDown(Keys.CONTROL).click(Initialsetupfirefox.driver.findElement(By.xpath("//a[contains(text(),'LOGIN')]")))
.keyUp(Keys.CONTROL)
.perform();
Thread.sleep(3000);
new Actions(Initialsetupfirefox.driver).sendKeys(Initialsetupfirefox.driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(Initialsetupfirefox.driver.findElement(By.tagName("html")),Keys.NUMPAD2).build().perform();
By this i am able to switch the focus but not able to do anything in this tab.
Please suggest
you can do like this:
Set<String> handles = driver.getWindowHandles();
String currentHandle = driver.getWindowHandle();
for (String handle : handles) {
if (!handle .equals(currentHandle))
{
driver.switchTo().window(handle);
}
}
//fill your form in the other tab
......
//go back to first tab if you want
driver.switchTo().window(currentHandle);
This it the code when using selenium with Node.js and Typescript
const mainHandle = await this.driver.getWindowHandle();
// load new tab here ..
const allHandles = await this.driver.getAllWindowHandles();
for (const handle of allHandles) {
if (handle !== mainHandle) {
await this.driver.switchTo().window(handle);
}
}
Get the browser-tabs and do as you like:
List<String> browserTabs = Lists.newArrayList(driver.getWindowHandles());
driver.switchTo().window(browserTabs.get(1)); // Switch to second tab
// Do something on second tab here...
driver.switchTo().window(browserTabs.get(0)); // Return to first tab
// Do something on first tab here...

Selenium Webdriver Java

I have a query on mouseover action in Selenium Webdriver Java.
Consider i have a background image with id "Lfade" with opacity 0.5. If i hover the mouse then a button would be shown.
I want to click on the button to take me to another screen. How do i do this ???
I have tried this, but it does not work
Actions builder = new Actions(driver);
WebElement tagElement = driver.findElement(By.id("Lfade"));
builder.moveToElement(tagElement).build().perform();
Html
div id="homeslant"
div id="wrapper"
div id="lFade" class="learn" style="opacity: 0.5; visibility: visible;"
Button
div class="descbtn"
a class="btn dwmbutton" href="/learn/index.html">KNOW MORE</a>
Not sure about what you are trying to do but I notice an error here:
builder.moveToElement(tagElement).build().perform();
Actually, the .perform() includes a .build().
May be you were referring to .click() so
builder.moveToElement(tagElement).click().perform()
As a pattern for your objective I would:
find the first image
move to the image
wait
find the button
click the button
I used Robot class for mouse hover. Please try the below code.
Robot robot = new Robot();
Point MyPoint = tagElement.getLocation();
robot.mouseMove(MyPoint.getX(), MyPoint.getY());
After that use the normal selenium click to click on the button.
You need to move to the button and perform a click.
Move to the image
wait
Move to the button and click
Actions act = new Actions(driver);
WebElement tagElement = driver.findElement(By.id("Lfade"));
act.moveToElement(tagElement).click().build().perform();
WebElement _button= driver.findElement(By...);
act.moveToElement(_button).click().build().perform();
Try this
#FindBy(xpath="//*[#id='chromemenu']/span/a") WebElement menuHoverLink;
#FindBy(xpath="//*[#id='dropmenu1']/a[1]") WebElement subLink;
Actions maction = new Actions(driver);
maction.moveToElement(menuHoverLink).build().perform();
Thread.sleep(2000);
subLink.click();
Use this code it will work :
Actions builder = new Actions(driver);
WebElement tagElement = driver.findElement(By.id("Lfade"));
WebElement buttonElement = driver.findElement(By.classname("btn"));
builder.moveToElement(tagElement).moveToElement(buttonElement).click().perform();
Try this
public void HoverAndClickObject(WebDriver driver, String property1, String property2, String path) throws SAXException, IOException, ParserConfigurationException
{
//get object properties from the xml file repository
Actions action = new Actions(driver);
String[] element1 = xmlParser(path, property1);
String[] element2 = xmlParser(path, property2);
switch (element1[0].toUpperCase())
{
case "XPATH":
driver.findElement(By.xpath(element1[1])).click();
action.moveToElement(driver.findElement(By.xpath(element2[1]))).click().build().perform();
break;
case "ID":
driver.findElement(By.id(element1[1])).click();
break;
case "NAME":
driver.findElement(By.name(element1[1])).click();
break;
case "LINKTEXT":
driver.findElement(By.linkText(element1[1])).click();
break;
case "CSSSELECTOR":
driver.findElement(By.cssSelector(element1[1])).click();
break;
}
}

Hyperlink.Click not being executed

I'm writing a Windows Phone Mango app. I have a hyperlink that contains email addresses. I want it to show a message box on tap:
Hyperlink href = new Hyperlink();
href.Click += (s, r) =>
{
MessageBox.Show("href clicked");
};
// add href to RichTextBox
When I click on the hyperlink in the emulator, nothing happens. The click += line is hit in a debugger, but the new EmailComposeTask() line isn't.
What am I doing wrong? Is Click not the event I want?
Update: I switched EmailComposeTask to MessageBox to verify that this issue isn't related to the email compose task not running on the emulator. I've reproduced this issue on my device.
The following code works:
GestureService.GetGestureListener(href); // adding this makes it work
href.Click += (s, r) =>
{
MessageBox.Show("href clicked");
new EmailComposeTask() { To = entireLink.Value }.Show();
};
href.Inlines.Add(new Run() { Text = entireLink.Value });
GetGestureListener creates a gesture listener if it doesn't already exist.
You should use HyperlinkButton Class, Hyperlink is a class used with rich text document rendering.
Following code is runs on device. text is RichTextBox object.
var linkText = new Run() { Text = "Link text" };
var link = new Hyperlink();
link.Inlines.Add(linkText);
link.Click += (o, e) =>
{
MessageBox.Show("Link clicked");
};
var paragraph = new Paragraph();
paragraph.Inlines.Add(link);
text.Blocks.Add(paragraph);

Resources