How to write rightclick method in selenium testng - selenium

How to do i rightclick on a webelement selenium testng?
i have given you example for doubleclick, likewise i need for rightclick method.please give me best one.
public static void doubleclickOn(String objLocator1){
try
{
findWebElement(objLocator1);
Actions actions = new Actions(driver);
org.openqa.selenium.interactions.Action action = actions.doubleClick(webElement).build();
action.perform();
APP_LOGS.debug("double Clicked on "+locatorDescription);
//System.out.println(locator);
}
catch(Exception e)
{
e.printStackTrace();
APP_LOGS.debug("FAIL : The locator "+locator+" of description "+locatorDescription+": does not exists in webpage:");
Reporting.fail("FAIL : The locator "+locator+" of description "+locatorDescription+": does not exists in webpage:");
}
}
thanks in advance

Try this:-
Assuming "objlocator1" consists of xpath of the webelement to right-click on.
public static void rightClickOn(String objLocator1){
try
{
findWebElement(objLocator1);
Actions actions = new Actions(driver);
actions.contextClick(driver.findElement(By.xpath(objLocator1)));
actions.perform();
APP_LOGS.debug("Context Clicked on "+locatorDescription);
//System.out.println(locator);
}
catch(Exception e)
{
e.printStackTrace();
APP_LOGS.debug("FAIL : The locator "+locator+" of description "+locatorDescription+": does not exists in webpage:");
Reporting.fail("FAIL : The locator "+locator+" of description "+locatorDescription+": does not exists in webpage:");
}

Right click action in Selenium web driver can be done using Actions class.
Also known as Context Click.
1) Below is the code to demonstrate right click operation using Actions class.
Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.id("ID"));
actions.contextClick(elementLocator).perform();
2) To select the item from the context menu
Actions action= new Actions(driver);
WebElement elementLocator = driver.findElement(By.id("ID"));
action.contextClick(elementLocator).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build().perform();
//adjust keys.ARROW_DOWN accordingly

Related

Whenever i perform click operation its navigating to footer instead of moving that page, and test case getting failed.Please give us some solution

We have used JS click and normal click but it's moving to the footer.
public static void jsClick(WebDriver driver, WebElement element,String msg) {
try {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);
WaitUtils.staticWait(5000); //3000
LoggerHelper.log().info(msg);
} catch (Exception e) {
LoggerHelper.log().error("Not able to click", e.getCause());
}
}
You don't click on a button in Selenium by injecting as JavaScript into it. You should use the Selenium driver in order to click:
element = driver.findElement(By.CSS, 'button[id="ButtonID"]')
element.click()
In you code example you are not using the Selenium plugin.

sendKeys(Keys.ARROW_DOWN) is not working while selecting location on Naukri homepage

I am new to selenium. I am trying to automate Naukri homepage.
However, in the field location, sendKeys(Keys.ARROW_DOWN) is not working. Code is working fine till a.sendKeys("ch").
I am using below code. Please guide.
driver.findElement(By.xpath("//input[#class='sugInp']")).sendKeys("java");
Thread.sleep(2000);
List<WebElement> options = driver.findElements(By.xpath("//ul[#class='Sdrop']/li/div/strong"));
for(WebElement o:options)
{
if(o.getText().equalsIgnoreCase("developer"))
{
o.click();
System.out.println("success");
break;
}
}
Thread.sleep(5000);
Robot r = new Robot();
r.keyPress(KeyEvent.VK_TAB);
System.out.println("Tab success");
Actions a = new Actions(driver);
a.sendKeys("ch");
a.sendKeys(Keys.ARROW_DOWN);
a.sendKeys(Keys.ARROW_DOWN);
a.sendKeys(Keys.ENTER);
a.build().perform();
I think you miss your element. Please try this one.
WebElement txtUsername = driver.findElement(By.id("email"));
Actions builder = new Actions(driver);
Action seriesOfActions = builder
.moveToElement(txtUsername)
.click()
.keyDown(txtUsername, Keys.SHIFT)
.sendKeys(txtUsername, "hello")
.keyUp(txtUsername, Keys.SHIFT)
.doubleClick(txtUsername)
.contextClick()
.build();
seriesOfActions.perform() ;
Why don't you just click on the desired element from the list, instead of using Actions
This is how it will look without Actions
driver.findElement(By.xpath("//input[#class='sugInp']")).sendKeys("java");
Thread.sleep(2000);List<WebElement> options = driver.findElements(By.xpath("//ul[#class='Sdrop']/li/div/strong"));
for (WebElement o : options) {
if (o.getText().equalsIgnoreCase("developer")) {
o.click();
System.out.println("success");
break;
}
}
Thread.sleep(3000);
driver.findElement(By.cssSelector("input#qsb-location-sugg.sugInp")).sendKeys("ch");
Thread.sleep(3000);
List<WebElement> elements = driver.findElements(By.xpath("//*[#id='sugDrp_qsb-location-sugg']/ul/li"));
System.out.println(elements.get(1).getText());
elements.get(1).click();
And don't use Thread.sleep() anywhere in your script, make sure to use waits.

selenium - submenu click not working

i am not able to click the submenu.. tried with different xpath/id .....
below is the html tags, Main Menu is Presentations(marked in red arrow) and submenus are under div.
can you please let me know how i can write xpath for this. i wanted to click hypothetical in the submenu.
here main menu tag is at the bottom of div(submenu).
also attached selenium code . please help me....
<div id="presentations" class="ToolbarSubMenu" align="left"parent="presentations_parent">
<a id="hypothetical" class="ToolbarMenu" href="">Hypothetical</a><br/>
</div>
<a id="presentations_parent" class="ToolbarMenu" href="">Presentations</a>
#Test
public void hypothetical()
{
WebElement ic = driver.findElement(By.id("presentations"));
Actions act = new Actions(driver);
// act.moveToElement(ic).click().build().perform();
//act.moveToElement(ic).doubleClick().build().perform();
act.moveToElement(ic).clickAndHold().release().build().perform();
//ic.click();
//driver.switchTo().window(myWindowHandle);
// driver.findElement(By.linkText("Hypothetical")).click();
// driver.findElement(By.xpath("//div[2][#id='presentations']/a[1]")).click();
//Actions act = new Actions(driver);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// WebElement hyp=driver.findElement(By.partialLinkText("Hypothetical"));
WebElement hyp=driver.findElement(By.id("//div[#id='presentations']/a[1]"));
//act.moveToElement(hyp).click().build().perform();
hyp.click();
Use below code:
//Click on main menu that will opens the sub Menu list
WebElement ic = driver.findElement(By.id("presentations"));
ic.click();
If your requirement is to click on each individual sub menu item,then use below code:
click for Hypothetical is:
ic.findElement(By.id("hypothetical")).click();
click for Profile is:
ic.findElement(By.id("profile")).click();
(Or)
You can also get all subMenu items at a time, like this:
//Get all the sub menu list.
List<WebElement> list = ic.findElements(By.tagName("a"));
for(int i=0;i < list.size; i++){
WebElement subMenuElement = list.get(i);
subMenuElement.click();
}
driver.findElement(By.id("presentations")).click();
WebElement hyp = driver.findElement(By.id("hypothetical"));
hyp.click();

wait on handler registering - selenium

There is a html page with button, and my selenium test is testing, that there is an action executed, when the button is clicked.
The problem is, that it looks like the click happens before the javascript is executed - before the handler is bound to the page. The consequence is, that the selenium test will click on the button, but no action happens.
I can solve this problem by repeatedly trying to click and then observe, if the desired action happened (some element is present on page, typically). I'd like to hear that there are some more elegant solutions...
There is no clear way to say "wait until element X has such-and-such handler"; this is a limitation of JavaScript and the DOM (see for example Get event listeners attached to node using addEventListener and jQuery find events handlers registered with an object), and for that matter a selenium Expected Condition can't be created, at least not trivially.
I've resorted to time.sleep(0.5).
You can write some logic to handle this.
I have write a method that will return the WebElement and this method will be called three times or you can increase the time and add a null check for WebElement
Here is an example
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.crowdanalytix.com/#home");
WebElement webElement = getWebElement(driver, "homekkkkkkkkkkkk");
int i = 1;
while (webElement == null && i < 4) {
webElement = getWebElement(driver, "homessssssssssss");
System.out.println("calling");
i++;
}
System.out.println(webElement.getTagName());
System.out.println("End");
driver.close();
}
public static WebElement getWebElement(WebDriver driver, String id) {
WebElement myDynamicElement = null;
try {
myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By
.id(id)));
return myDynamicElement;
} catch (TimeoutException ex) {
return null;
}
}

selenium code to select radio button

Am doing automation tesing using selenium, i need help in regarding how to select radio button.If possible help me with selenium java code.
Assuming you have selenium set up its just:
selenium.click('radio button locator');
You may want to look at the selenium javadoc http://release.seleniumhq.org/selenium-remote-control/0.9.2/doc/java/com/thoughtworks/selenium/Selenium.html
click > xpath=(//input[#type='checkbox'])[position()=1]
click > xpath=(//input[#type='checkbox'])[position()=2]
click > xpath=(//input[#type='checkbox'])[position()=3]
click > xpath=(//input[#type='checkbox'])[position()=4]
etc ...
use this commands to select random and any radio button
public class radioExamJavaScr {
public static void main(String[] args) throws IOException {
WebDriver driver = new FirefoxDriver();
EventFiringWebDriver dr = new EventFiringWebDriver(driver);
dr.get("http://www.makemytrip.com/");
dr.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
((JavascriptExecutor)dr).executeScript("document.getElementById('roundtrip_r').click();");
WebElement one_way = (WebElement)((JavascriptExecutor)dr).executeScript("return document.getElementById('oneway_r') ;");
System.out.println(one_way.isSelected());
WebElement round_trip = (WebElement)((JavascriptExecutor)dr).executeScript("return document.getElementById('roundtrip_r') ;");
System.out.println(round_trip.isSelected());
}
}
In the above example I am selecting radio button with "ROUND TRIP" using "JavaScript".
The last four lines are to verify and see whether the expected radio button is selected in the page or not.
NOTE: I am giving simple easy solution to solve a problem (selecting a radio) in the choosen webpage. A better code can be written. (user can write a method to accept radio ID and loop through all the existing radio button to see which one of them is selected).
I use this method:
String radioButtonId = "radioButtonId";
selenium.focus("id=" + radioButtonId);
selenium.click("id=" + radioButtonId, "concreteRadioButtonValue");
What you can do is this:
Create a method with a WebElement return type, and use the Method findElement(). Example:
WebDriver test;
test = new FirefoxDriver();
public static WebElement checkAndGet(By b) throws Exception {
return test.findElement(b);
}
Store the WebElement and use the Method click(). Example:
WebElement radiobutton = checkAndGet(By.xpath("//span[#class='label ng-binding']");
radiobutton.click();
Hope this helps!
Test Scenario : Select Gender(Female) radio button
Steps:
Launch new Browser
Open URL http://toolsqa.wpengine.com/automation-practice-form/
Select the Radio button (female) by Value ‘Female’
Code :
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver(); // Step 1 - Launch Browser
driver.get("http://toolsqa.com/automation-practice-form"); // Step 2 - Open Test URL
List<WebElement> rdBtn_Sex = driver.findElements(By.name("sex")); //
int size = rdBtn_Sex.size();
System.out.println("Total no of radio button :"+size);
for (int i=0; i< size; i++)
{
String sValue = rdBtn_Sex.get(i).getAttribute("value"); // Step 3 - 3. Select the Radio button (female) by Value ‘Female’
System.out.println("Radio button Name "+sValue);
if (sValue.equalsIgnoreCase("Female"))
{
rdBtn_Sex.get(i).click();
}
}
What you should do all the time is provide a locator for every object within a page and then use a method.
Like
driver.findElement(By.xpath(//CLASS[contains(., 'what you are looking for')])).click();