selenium - submenu click not working - selenium

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();

Related

Selenium Button Click() or Submit()?

Need help on following scenario(using Java):
Doing it manually like this: after filling in some info in a parent page, clicking Continue button on it,
<INPUT TYPE='button' VALUE='Continue' onClick='sendForm()'>
A child window(UserConfirmationPage) pops up with those info from its parent window, clicking the Continue button on the child page, posting the data to server.
<FORM NAME='userConf' ACTION='user.jsp' METHOD='post'>
Do you want to continue?<BR>
<INPUT TYPE='button' VALUE='Continue' onClick='createUser()'>
</FORM>
However, when I do it using Selenium Web Driver, on the parent page,
btnContinue.submit()
a child page pops up with those info from parent page just like what I got when I do it manually but parent does not exist any more. While using
btnContinue.click()
a blank child page is opened without getting any info from parent page and it also complains "session is lost".
I also tried:
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].click();",btnContinue);
and
new Actions(driver).moveToElement(driver.findElement(By.xpath("//input[#value='Continue']"))).click().perform();
but nothing works.
It seems that neither Submit() nor Click() could simulate what was done manually. Any idea?
Thanks a lot in advance!
You did not specify the language, so I assume you're using JAVA:
// since new tab has been opened - need to switch to this tab
// get a list of the currently open windows
Set<String> allTabs = driver.getWindowHandles();
// save the window handle for the current window
String programTab = driver.getWindowHandle();
// switching to the Save tab
String saveTab = ((String) allTabs.toArray()[1]);
driver.switchTo().window(saveTab);
// set timeout
// Click button
driver.findElement(By.id("buttonId")).click();
// set timeout
// switch back to the program tab
driver.switchTo().window(programTab);
Try this it is simplest and easiest code which help you to understand Parent and child scenario.
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://demo.guru99.com/popup.php");
driver.findElement(By.xpath("html/body/p/a")).click();
// return the parent window name as a String
String parentWindow=driver.getWindowHandle();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Pass a window handle to the other window
for(String childWindow: driver.getWindowHandles())
{
System.out.println("child");
//switch to child window
driver.switchTo().window(childWindow);
//find an element and print text of it
WebElement textLabel=driver.findElement(By.xpath("html/body/div[1]/h2"));
System.out.println(" text: "+textLabel.getText());
driver.close();
}
System.out.println("Come to parent window");
//switch to Parent window
driver.switchTo().window(parentWindow);
//find an element and print text of it
WebElement logotext=driver.findElement(By.xpath("html/body/div[1]/h2"));
System.out.println("text: "+logotext.getText());
driver.close();
}

PhantomJS submit button not clicked - works in Selenium

I am having difficult with the submit button, it is not clicked in phantomJS the same code when run in Selenium works.
Does anybody have any suggestions (in Java) ?
public class BookFlight
{
WebDriver driver;
File file = new File("C:/Program Files/phantomjs-2.1.1-windows/bin/phantomjs.exe");
#Test
public void homePageFlightDetails() throws Exception
{
//Setup GhostDriver
System.setProperty("phantomjs.binary.path", file.getAbsolutePath());
//***************************************************
// FIREFOX UI DEBUG - Set debug to True for UI debug
boolean debug=false;
if (debug)
{
driver= new FirefoxDriver();
driver.manage().window().maximize();
}
else
{
driver=new PhantomJSDriver();
//Set logging to Severe Logger.getLogger(PhantomJSDriverService.class.getName()).setLevel(Level.SEVERE);
}
//***************************************************
//Submit Home page and get the title
driver.get("http://www.aa.com");
String pageTitle = driver.getTitle();
System.out.println("The Current page title is "+pageTitle);
//Find the origin airport field
WebElement originAirport=driver.findElement(By.id("reservationFlightSearchForm.originAirport" ));
//Clear any existing text and enter the origin airport
originAirport.clear();
originAirport.sendKeys("PHX");
//Find the destination airport field
WebElement destAirport=driver.findElement(By.id("reservationFlightSearchForm.destinationAirport" ));
destAirport.clear();
destAirport.sendKeys("LAS");
//Find the depart date field
WebElement depDate = driver.findElement(By.id("aa-leavingOn"));
depDate.clear();
depDate.sendKeys("08/20/2016");
//Find the return date field
WebElement retDate = driver.findElement(By.id("aa-returningFrom"));
retDate.clear();
retDate.sendKeys("08/24/2016");
//Find the Search up button
// WebElement searchButton = driver.findElement(By.id("flightSearchForm.button.reSubmit"));
// driver.findElement(By.id("flightSearchForm.button.reSubmit")).click();
// WebElement searchButton = driver.findElement(By.xpath("//*[#value='Search'][#type='submit']"));
//phantomjs debug - Verify the button has been found
boolean buttonText = driver.findElement(By.xpath("//*[#value='Search'][#type='submit']")).isDisplayed();
System.out.println("buttonText Boolean is = "+buttonText);
//Click the Search button
//driver.findElement(By.xpath("//*[#value='Search'][#type='submit']")).sendKeys(Keys.RETURN);
//*********** This works in Selenium ***********
driver.findElement(By.xpath("//*[#value='Search'][#type='submit']")).click();
// Wait for the Choose Flights page to appear
int count = 1;
do
if (driver.getTitle().contains("Choose flights"))
{
break;
}
else
{
System.out.println("do loop iteration "+count+ " the title = "+ driver.getTitle());
Thread.sleep(1000);
count++;
}
while (count < 30);
System.out.println("After search the current page title is = "+ driver.getTitle());
Assert.assertTrue(driver.getTitle().contains("Choose flights"));
driver.quit();
}
I'm encountering a similar issue when using phantomjs via Jmeter (with WebDriver Sampler).
What I can see is that a modal exists on the page which is overlaying the fields I need to interact with. I can add assertions to verify the fields and buttons exists and capture their values, just cant click on the button.
The only workaround that I can think of is calling the function (button onclick function) although not my preference.

How to write rightclick method in selenium testng

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

How to select an element from a menu using Webdriver Selenium ? The Menu drop down shows up on Mouse Over?

How to select an element from a menu using Webdriver Selenium ? The Menu drop down shows up on Mouse Over?
You can check it in two ways:
1) first way is to use actions builder
WebElement mnuElement;
WebElement submnuElement;
mnEle = driver.findElement(By.Id("mnEle")).Click();
sbEle = driver.findElement(By.Id("sbEle")).Click();
Actions builder = new Actions(driver);
// Move cursor to the Main Menu Element
builder.MoveToElement(mnEle).Perform();
// Giving 5 Secs for submenu to be displayed
Thread.sleep(5000L);
// Clicking on the Hidden SubMenu
driver.findElement(By.Id("sbEle")).Click();
See here
2) another approach is to click directly needed element using jscript without simulating mouse hover event:
String cssLocatorOfTheElement=....//locator of the element to click on
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("var x = $(\'"+cssLocatorOfTheElement+"\');");
stringBuilder.append("x.click();");
js.executeScript(stringBuilder.toString());
hope this works for you)
Simulate mouseOver event and then select element you can like that:
var elementToShowMenu = Driver.FindElement(Byl.Id("some id"));
new Actions(Driver).MoveToElement(elementToShowMenu).Release(elementToShowMenu).Build().Perform();
var menuElement = Driver.FindElement(Byl.Id("your menu id"));
Here is how I click a invisible anchor link on a tag: a link that is generated dynamically by Javascript:
public static void mouseClickByLocator( String cssLocator ) {
String locator = cssLocator;
WebElement el = driver.findElement( By.cssSelector( locator ) );
Actions builder = new Actions(driver);
builder.moveToElement( el ).click( el );
builder.perform();
}
WebElement mnuElement;
WebElement submnuElement;
mnuElement = driver.findElement(By.cssSelector("insert selector here"));
submnuElement = driver.findElement(By.cssSelector("insert selector here"));
Actions builder = new Actions(driver);
// Move cursor to the Main Menu Element
builder.moveToElement(mnuElement).perform();
// Pause 2 Seconds for submenu to be displayed
TimeUnit.SECONDS.sleep(2); //Pause 2 seconds
// Clicking on the Hidden submnuElement
submnuElement.click();

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();