As I am aware that user can click on Particular Webelement by using click method and one more way like using Sendkey Method with ASCII Value for left Click.
By Click Method: driver.findElement(By.cssSelector(".dbl")).click();
By Ascii Value : driver.findElement(By.cssSelector(".dbl")).sendKey("ASCII VALUE FOR Left Click");
Apart from this is there a way to perform click action??
You can use:
yourelement.sendKeys(Keys.RETURN) or .sendKeys(Keys.ENTER) : which is an equivalent of focusing that element and hitting RETURN/ENTER on that element
Also, There are methods to do this using Javacript but it is not usually recommended:
using the non-native Javascript Executor:
((JavascriptExecutor) driver).executeScript("arguments[0].click();", yourelement);
or by using Javascript Library:
JavascriptLibrary jsLib = new JavascriptLibrary();`
jsLib.callEmbeddedSelenium(driver, "triggerMouseEventAt", we, "click", "0,0");
Below are some methods that will be useful to click a button/Image.
WebDriver driver = new ChromeDriver();
driver.get("http://newtours.demoaut.com");
WebElement signOnImage = driver.findElement(By.xpath("//input[#type='image'][#name='login']"));
// direct method from the API which is recommended always
signOnImage.click();
1 Using Return Key
//signOnImage.sendKeys(Keys.RETURN);
2 Using JavascriptExecutor
2.1
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", signOnImage);
2.2
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementsByName('login')[0].click()");
3 Using Actions class
3.1
Actions actions = new Actions(driver);
actions.click(signOnImage).perform();
3.2
Actions actions = new Actions(driver);
actions.moveToElement(signOnImage).click().perform();
3.3
Actions actions = new Actions(driver);
actions.clickAndHold(signOnImage).release().perform();
3.4
Actions actions = new Actions(driver);
actions.sendKeys(signOnImage, Keys.RETURN).perform();
submit();
If the current element is a form, or an element within a form, then this will be submitted to the remote server. If this causes the current page to change, then this method will block until the new page is loaded
There are four typical ways to perform click in Selenium-Java bindings.
Using findElement
driver.findElement(By.xpath("//span[text()='Excel']")).click();
Using WebDriverWait
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='Excel']"))).click();
Using executeScript
WebElement button = driver.findElement(By.xpath("//span[text()='Excel']"));
((JavascriptExecutor)driver).executeScript("arguments[0].click();", button);
Using ActionClass
WebElement button = driver.findElement(By.xpath("//span[text()='Excel']/parent::button[#aria-controls='report'][contains(#class,'downloadExcel')]"));
new Actions(driver).moveToElement(button).click().build().perform();
I am using xpath, you can use css, linkText, tagName, name, partialLinkText etc as well to perform click.
If you want to click a button or set an value to an web element through selenium you can use XPATH variable ,for using XPATH variable you must find the value of it ,you can find it using Firefox browser and few add_on's like firebugs .
driver.findElement(By.xpath(".//*[#id='main']/div[4]/div/button")).click();
I would suggest you to use XPATH variable so that you can locate any web element in a webpage.
If you want find the hyperlink web element then you can use By.linkText when you are sure about the tag name or choose By.partialLinkText by which you can locate even if you partial web element name but in this case your partial search key matches more than one element then By.partialLinkText won't works fine.
For example,in case you knows the complete tag name of hyperlink use can use
driver.findElement(By.linkText("Click to Next Page")).click();
or else
Where you knows only a partial tag name
driver.findElement(By.linkText("Next Page")).click();
The secound option will not help you in all instances.
HTMLElement.click()
The HTMLElement.click() method simulates a mouse click on an element. At the core level when click() is used with supported elements e.g. <a>, <button>, <input>, etc, it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
There are several ways to invoke the click() method as follows:
Element click(): This Element Click command scrolls into view the element if it is not already pointer-interactable, and clicks its in-view center point. An example:
driver.findElement(By.linkText("Selenium")).click();
Element sendKeys(Keys.SPACE): An example:
driver.findElement(By.linkText("Selenium")).sendKeys(Keys.SPACE);
Actions click(): Clicks at the current mouse location. Useful when combined with moveToElement(org.openqa.selenium.WebElement, int, int) or moveByOffset(int, int). An example:
new Actions(driver).click(element).build().perform();
Actions doubleClick(): Performs a double-click at the current mouse location. An example:
new Actions(driver).keyDown(Keys.CONTROL).doubleClick(link).keyUp(Keys.CONTROL).build().perform();
Action sendKeys(textToSend, Keys.RETURN): An example:
new Actions(driver).moveToElement(element).sendKeys(textToSend, Keys.RETURN).perform();
Action sendKeys(textToSend, Keys.ENTER): An example:
new Actions(driver).moveToElement(element).sendKeys(textToSend, Keys.ENTER).perform();
Actions contextClick(): Performs a context-click at the current mouse location. An example:
new Actions(driver).contextClick(element).build().perform();
JavascriptExecutor executeScript​(): Executes JavaScript in the context of the currently selected frame or window. The script fragment provided will be executed as the body of an anonymous function.
((JavascriptExecutor)driver).executeScript("arguments[0].click()", webElement);
Submit(): Applicable if this current element is a form, or an element within a form.
WebElement searchButton = driver.findElement(By.xpath("//button[#type='submit']"));
searchButton.submit();
Mouse Double Click
Mouse Triple Click
Related
Click button via class because it has no ID . Or via value?
tried className , cssSelector , partialLinkText and LinkText but sadly did not work clicking the save button
System.out.println("Succesful in Saving Product ");
WebElement save = driver.findElement(By.className("bttn-positive save-button"));
save.click();
Should be able to click save button
we can not use the multiple class name in the className locator. So, you can use the XPath locator with the multiple class name as below (//input[#class='bttn-positive save-button'])
Code:
System.out.println("Succesful in Saving Product ");
WebElement save = driver.findElement(By.xpath("//input[#class='bttn-positive save-button']"));
save.click();
You can't pass multiple classnames while using driver.findElement(By.className("bttn-positive save-button")) and doing so you will face Invalid selector: Compound class names not permitted error.
To click() on the green button with text as Save you have to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.bttn-positive[value^='Save'][type='button']"))).click();
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[contains(#class, 'bttn-positive') and starts-with(#value, 'Save')][#type='button']"))).click();
Try save.submit();
Submit buttons are used to submit the entire form to the server. We can either use the click () method on the web element like a normal button as we have done above or use the submit () method on any web element in the form or on the submit button itself.
In this case "save.click()" will be work, but some time to save any product on any app like eCommerce or Banking domain it will not working properly & one more important think click () cause a new page to load, this method will attempt to load the page . So better to use "save.submit()" if the current elements is form Or with in the form the this will be submitted. As up ur requirements submit () one is the better option.
I am getting a very long xpath for an element that I selected. Is there anyway to shorten it? This is the xpath I am getting:
//li[#class='menu_men 1-level hasChild']//div[contains(#class,'level-2')]//div[#class='menu-wrapper']//ul[#class='level-2']//li[#class='1-level']//div[#class='level-3']//ul[#class='level-3']//li//a[#class='level-3'][contains(text(),'Socks')]
This is the URL: Calvin Klein Singapore I hovered over 'MEN', the accessories section will appear, than I hover the 'Socks' to get the xPath.
I am getting the following execption in my code and I am wondering if somehow the long xpath could be one of the reasons:
org.openqa.selenium.NoSuchElementException: no such element: Unable to
locate element: {"method":"xpath","selector":"//li[#class='first
menu_men 1-level
hasChild']//div[contains(#class,'level-2')]//div[#class='menu-wrapper']//ul[#class='level-2']//li[#class='1-level']//div[#class='level-3']//ul[#class='level-3']//li//a[#class='level-3'][contains(text(),'Socks')]"}
I am using cropath from within chrome developer tools to get the xPath.
I am new to automation, I really hope someone can advise. Thank you.
#SameerArora this is the code I have to clear the pop up window, as what I had mentioned in the comments below.
//for clearing the popup window
#FindBy(how=How.XPATH,using="//*[starts-with(#id,'popup-subcription-closes-link-')]")
public WebElement newsletterpopup;
public String clickCategory(){
//.....
resusableFunctions.buttonClick(driver, newsletterpopup, "popoup");
}
public void buttonClick(WebDriver driver, WebElement element, String elementName) throws InterruptedException
{
try
{
element.click();
System.out.println("Log: ResuableFunction.buttonClick");
}
catch (org.openqa.selenium.ElementNotInteractableException notInteract)
{}
The element you are looking for can be found using xpath:
WebElement element = driver.findElement(By.xpath("(//a[contains(text(),'Socks')])[1]"));
However, as the element is not visible directly when you are opening the link, you would be getting NoSuchElementException, so to resolve it you can use javascript click method on the element which directly operates on the div of the page.
Addition to this, i can see that a subscription popup comes when i am opening the page for the first time, so you need to dismiss that popup first(if the popup is present) and then click on the "Socks" element using the JavaScript click method.
Your code should be like:
List<WebElement> closeSubscriptionPopUp = driver.findElements(By.xpath("//a[contains(#id,'popup-subcription-closes-link')]"));
if (closeSubscriptionPopUp.size() > 0) {
closeSubscriptionPopUp.get(0).click();
}
WebElement sockElement = driver.findElement(By.xpath("(//a[contains(text(),'Socks')])[1]"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", sockElement);
To hovered over 'MEN' >> accessories >> 'Socks' section, You need to use selenium Actions class.
As it is not really possible to first click on men(as it will open other section),
So to hover to sock, you need to chain all of the actions that you want to achieve in one go.
Process should be:
move to men element first
Move to accessories
then move to Socks and click on it.
Note: By using Action class, we can chain all the process in one single go.
As mentioned below
1) First way:
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("(//a[contains(text(),'MEN')])[2]")))
.moveToElement(driver.findElement(By.xpath("(//a[contains(text(),'Socks')])[1]")))
.click().build().perform();
2) Second way with wait:
WebDriverWait wait= new WebDriverWait(driver, 10);
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("(//a[contains(text(),'MEN')])[2]"))).build().perform();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//a[contains(text(),'Socks')])[1]")));
action.moveToElement(driver.findElement(By.xpath("(//a[contains(text(),'Socks')])[1]")));
action.click().build().perform();
Try this:
//a[normalize-space(text()) = 'Socks']
I would recommend you to not use such long xpath's and try to write xpath on your own.
Try :
//li[contains(#class,'menu_men')]//a[contains(text(),'Socks')]
Following is the sample HTML code of the page:
I'm trying to mouse hover on the element with following xpath:
WebElement Bar1 = dvr.findElement(By.xpath("//div[#class='barModel']/div[#class='model']/canvas[#class='segment']")));
Following is the code
act = new Action (driver);
act.moveToElement(Bar1).build().perform();
act.clickAndHold();
My objective is to drag the element. Running the above code doesn't give any error but there is no visible interaction on the page. I am able to do this task using Robot class but just curious to make it happen using Action class.
You didn't performed clickAndHold action:
act = new Action (driver);
act.moveToElement(Bar1).build().perform();
act.clickAndHold().perform();
If you want to drag and drop element you can just use build-in function:
act.dragAndDrop(movedElement, targetElement).perform();
You can use JavaScriptExecutor to perform mouseover as like below :-
JavascriptExecutor js = (JavascriptExecutor) dvr;
js.executeScript("var clickEvent = document.createEvent('MouseEvents');clickEvent.initEvent('mouseover', true, true); arguments[0].dispatchEvent(clickEvent);", Bar1);
By using above Java Script you can perform mouseover. Now you can use dragAndDrop to move element as below :-
Actions action = new Actions(dvr)
action.dragAndDrop(sourceElement, destinationElement).build().perform()
Hope it will help you...:)
I'm trying to write some Selenium tests to test Pandora FMS using the Java implementation of the webdriver exported by the Selenium IDE.
The initial login part works just fine:
driver = new FirefoxDriver();
baseUrl = "http://brmew.lab.brmew.es";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl + "/pandora_console/index.php");
driver.findElement(By.id("nick")).clear();
driver.findElement(By.id("nick")).sendKeys("my");
driver.findElement(By.id("pass")).clear();
driver.findElement(By.id("pass")).sendKeys("credentials");
driver.findElement(By.id("submit-login_button")).click();
Then, the problematic part, which is clicking a menu. I've tried to do the most simple approach:
driver.findElement(By.xpath("//ul[#id='subViews']/li[4]/a/div")).click();
But it did not work, so I tried:
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[#id='subViews']")));
myDynamicElement.click();
You can find the HTML I'm testing this with in this link (it's way too large to paste it here)
Hidden menu
Shown menu
Are you getting any exception? It seems that the element submemu item you are trying to click is invisible. If it get displayed on main menu click or mouse over you need to do that before perform click action to the element. For Example:
//Click main menu to open submenu
driver.findElement(By.xpath(".//*[#id='Views']/div")).click();
//now access submenu
driver.findElement(By.xpath(".//ul[#id='subViews']/li[4]/a")).click();
Or alternately more preferable way is:
WebElement viewsMenu = driver.findElement(By.xpath(".//*[#id='Views']/div"));
viewsMenu.click();
//or mouse over
Actions action = new Actions(webdriver);
action.moveToElement(viewsMenu).build().perform();
//now access submenu
viewsMenu.findElement(By.xpath(".//ul[#id='subViews']/li[4]/a")).click();
From ur given link, i can't find the monitoring > views > agent detail
But it seems that first u have to click on
monitoring and than wait
than click on
views and wait
than click on ur
agent detail
for mouse hover use the below code
//get element as ur wish by css or xpath or id
WebElement elem = driver.findElement(By.cssSelector("ur locator"));
Actions builder = new Actions(driver);
builder.moveToElement(elem).perform();
makeWait(5);
than after showing the element, than again get next element and use the code for hover.
There is an invisible element on my HTML page which becomes visible when a mouse hover is done on the element. What I Have to do is
Hover over the element
Click on the element (it will display 4 options)
Click on one of the options
I am using Java API for selenium web driver and following is what I have been trying
Actions builder = new Actions(driver);
builder.moveToElement(MainMenuBTN).click().build().perform();
subMenuBTN.click();
MainMenuBTN = element that becomes visible when you hover the mouse
over it
subMenuBTN = element that is being chosen out of the menu options
that are displayed
What is happening is, the click() on MainMenuBTN is generating ElementNotVisible exception.
I tried following to avoid this, but did not work.
Actions builder = new Actions(driver);
builder.moveToElement(mainMenuBTN).build().perform();
builder.click();
subMenuBTN.click();
A Note : mainMenuBTN and subMenuBTN are WebElements generated by
driver.findElement(By.xpath("xpath_string"))
Am I missing anything? Help appreciated !
Well, after going through your questions numerous times and changing my answers many times I will go with -
Issue - what I got from the original code -
You need to move the cursor to the mainMenuBTN (which is visible not the element that becomes visible when you hover the mouse over it ) and subMenuBTN is then displayed which you need to click.
The only edit to your original code as per me will be adding a statement to move the cursor to your subMenuBTN before you click it. This way works fine for me when I need to click sub menu item.
Actions builder = new Actions(driver);
builder.moveToElement(mainMenuBTN).build().perform();
builder.moveToElement(subMenuBTN).build().perform();
subMenuBTN.click();
Please let me know if this is the case.
using javascript executor like
((JavascriptExecutor) webdriver).executeScript("document.getElementById('btn').click();");
Your Actions builder looks slightly wrong to me. Here is a example I use:
public static void mouseClickByLocator( String locator ) {
WebElement el = driver.findElement( By.cssSelector( locator ) );
Actions builder = new Actions(driver);
builder.moveToElement( el ).click( el );
builder.perform();
}
Actions builder = new Actions(driver);
builder.MoveToElement(menu).MoveToElement(submenu).Click().Perform();
It works under Chrome, but doesn't work in FF
You could try this:
Get your WebElement by its xpath.
Hover element.
Get your WebElement by its xpath again.
Click it.
It's because of element's id is changing when you hover over it and you should find it again.
Actions builder = new Actions(driver);
WebElement mainMenuBTN = getWebEl("xpath_string",5);
builder.moveToElement(mainMenuBTN).perform();
mainMenuBTN = getWebEl("xpath_string",5);
builder.click(mainMenuBTN);
I use this method to ipmlement controlled explicit wait into my elements' instantiation.
protected WebElement getWebEl(String xpath, int waitSeconds) {
wait = new WebDriverWait(driver, waitSeconds);
return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
}
My case we had a table of rows, if mouse over on the row, one of the column(td) should display some 4 icons, we should click on it.
Action action=new Action(driver);
action.moveToElement(hoverElt).clickAndHold().build().perform();
It worked for me.
moveToELement() move your control to the element
clickAndHold() clicks and holds the hovered element, so that its easy for us to do operation on visible elements.