Xpath issue in element location - java

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')]

Related

click on a button with JQuery

There is somthing wrong with the page I want to test.
My first try:
When I clicked manually on a button, then I will be forwarded normally on the next page.
When I tried to click on the same button with selenium, then I get an error page "Sorry...something gone wrong...blabla". I think this problem can only solve the developer team of the page.
By book = By.cssSelector("#button\\.buchung\\.continue");
//By book = By.cssSelector("button.buchung.continue");
//By book = By.xpath("//*[#id='button.buchung.continue']");
WebElement element= ConfigClass.driver.findElement(book);
element.click();
But I want to try a workaround:
I clicked on the same button with JQuery.
I opened my chrome console and execute the button with:
jQuery('#button\\.buchung\\.continue').click()
How can I execute this JQuery expression in my selenium code?
I tried this, but without success:
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("jQuery('#button\\.buchung\\.continue').click()");
Use $
je.executeScript("$('#button\\.buchung\\.continue').click()");
jQuery("selector") will return you a list.
I think you have to call click() on the element at index 0 (Assuming exactly one element satisfies the selector)
Code:
je.executeScript("jQuery('#button\\.buchung\\.continue')[0].click()");
You were pretty close. If the cssSelector is uniquely identifying the WebElement you can use the following code block :
By book = By.cssSelector("#button\\.buchung\\.continue");
WebElement element= ConfigClass.driver.findElement(book);
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);

Selenium - Unable to click on link from dropdown list

I am trying to click on a link from a dropdown list in the menu. Selenium seems to be able to find the element. But not able to click on it and giving the below exception:
Exception in thread "main" org.openqa.selenium.ElementNotInteractableException: Cannot click on element
I am using IEDriver to run the code.
Below is the java code I am using to find and click on the element:
File file = new File("C:\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();
driver.manage().window().maximize();
driver.get("url");
driver.findElement(By.xpath("//*[#id=\"Ul1\"]/li[2]/a")).click();
driver.findElement(By.xpath("//*[#id=\"Ul1\"]/li[2]/ul/li[1]/a")).click();
Below is the HTML body:
<body><ul class="sf-menu" id="Ul1"><li class = "current"><a target="bodyFrame" href="http://hostname.default.aspx">Home</a><ul></ul></li><li class = "current">Create Usage<ul><li class="current"><a target="bodyFrame" href="../SAMPLEAPPDT/Usage.htm" title="Usage Generator (SAMPLEAPP Rating)"">Usage Generator</a> <ul></ul></li><li class="current"><a target="bodyFrame" href="../NETWORKUG/network_usage/NETWORKUsageUpload.aspx?appId=1" title="NETWORK"">NETWORK</a><ul></ul></li><li class="current"><a target="bodyFrame" href="../NETWORKUG/network_usage/NETWORKUsageUpload.aspx?appId=2" title="RSS Usage Generator"">RSS</a><ul></ul></li></ul></li></ul><iframe name="bodyFrame" id="bodyFrame" src="" width="100%" frameborder="no"></iframe></body>
Please let me know what could be the issue
Assuming you are using some JavaScript code to open/close this dropdown, you might need to wait for the dropdown to open before you can select the element because it is not yet visible. Your second "click" might be too fast after the first one.
For example, you can implicitely wait for a certain
amount of time like so:
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
A better alternative would be to wait for your element to be visible like this:
WebDriverWait webDriverWait = new WebDriverWait(driver, 10);
webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id=\"Ul1\"]/li[2]/ul/li[1]/a")));
Do this after you click the first "a" element and before you try to click on the second.
Thanks for the responses.
The issue seems to be that after selenium clicks on the menu, the list shows up and disappears again. So the second findElement i was using to click on the link in the menu dropdown was not working since selenium is not able to find the element.
I was able to resolve the issue by making selenium hover over the menu and clicking on the first link in the list
Below is the code I used:
Actions action = new Actions(driver);
WebElement webelement = driver.findElement(By.xpath("//*[#id=\"Ul1\"]/li[2]/a"));
action.moveToElement(webelement).moveToElement(driver.findElement(By.xpath("//*[#id=\"Ul1\"]/li[2]/ul/li[1]/a"))).click().build().perform();
Java with Selenium Webdriver: Unable to click On the link list but I am able to print out all the link.
I also tried to click on the link using : linktext, href,JS, xpath, CSS, action.double click and click.
//this is my code
WebElement hometab=driver.findElement(By.xpath("//*[#id='new_nav']/li[1]/a"));
hometab.click();
List<WebElement> homelist1=driver.findElements(By.xpath("//ul/ul/li[1]/ul/li/a"));
int allLinks = homelist1.size();
for(int i=0;i<=allLinks;i++) {
List<WebElement> homelis=driver.findElements(By.xpath("//*[#id='main_form']/div[2]/div/ul/ul/li[1]/ul/li"));
WebElement homelis11=driver.findElement(By.xpath("//ul/ul/li[1]/ul/li[1]"));
System.out.println(homelis.get(i).getText());
WebElement element = homelis.get(i);
System.out.println(homelis.get(i));
System.out.println(homelis.get(i).getText());
homelis11.click();
element.submit();
System.out.println("Inside action class");
Actions actions = new Actions(driver);
actions.moveToElement(homelis11).click().build().perform();
System.out.println("JS click ");
//js click
JavascriptExecutor exec = (JavascriptExecutor) driver;
exec.executeScript("arguments[0].click()", homelis11);
//verify the text on that page
WebElement textq=driver.findElement(By.xpath("//h1"));
System.out.println(textq.getText()+UIActions.tab);
//back to home page with all the menu list
driver.navigate().back();
Thread.sleep(15);
Identify the select HTML element:
WebElement mySelectElement = driver.findElement(By.id("mySelect"));
Select dropdown= new Select(mySelectElement);
or pass it directly to the Select element:
dropdown = new Select(driver.findElement(By.id("mySelect")));
To select an option you can do:
All select/deselect methods will throw NoSuchElementException if no matching option elements are found.
Select by Visible Text (select all options that display text matching the argument):
dropdown.selectByVisibleText("Italy");
or
Select by Index (select the option at the given index. This is done by
examining the “index” attribute of an element, and not merely by counting):
dropdown.selectByIndex(2);
http://loadfocus.com/blog/2016/06/13/how-to-select-a-dropdown-in-selenium-webdriver-using-java/

Webdriver not finding xpath element

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.

How many ways to click on webElement In WebDriver?

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

How to Hover over and click on an invisible element using selenium webdriver?

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.

Categories