Selenium: click on <li> - java

I have the following html code and I want to click on the second option "Plan b".
<ul class="clearfix all">
<li data-content="a" data-tab-target="tab1" class="active"><span>Plan a</span</li>
<li data-content="b" data-tab-target="tab2" class=""><span>Plan b</span></li>
<li data-content="c" data-tab-target="tab3" class=""><span>Plan c</span></li>/ul>
I tried to do somthing like this:
1.
#FindBy(css = "li:nth-child(2)")
WebElement sparpreis;
sparpreis.click();
2.
#FindBy(xpath = "//*[#class='clearfix all']/ul/li[2]")
WebElement sparpreis;
sparpreis.click();
My error messages:
org.openqa.selenium.ElementNotVisibleException: element not visible
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[#class='clearfix all']/ul/li[2]"}
Perhaphs I should activate the second "class"?

The /ul is not needed, try the following:
#FindBy(xpath = "//ul[contains(#class, 'clearfix all')]/li[2]")

As per the HTML you have shared, to click on the second option Plan b you can use either of the following code block :
css
#FindBy(css = "ul.clearfix.all li[data-content=b] > span")
WebElement sparpreis;
sparpreis.click();
xpath
#FindBy(xpath = "//ul[#class='clearfix all']//li[#data-content='b']/span")
WebElement sparpreis;
sparpreis.click();

Related

How to identify the text within the <a> using Selenium and Java

This is the code of the demo store I want to test:
<li class="level0 nav-2 parent">
<a href="http://demo-store.seleniumacademy.com/men.html"
class="level0 has-children">Men</a>
<ul class="level0">
<li class="level1 view-all">
<a class="level1" href="http://demo-
store.seleniumacademy.com/men.html">View All
Men</a>
</li>
<li class="level1 nav-2-1 first"><a></a></li>
<li class="level1 nav-2-2"><a href="http://demo-
store.seleniumacademy.com/men/shirts.html"
class="level1">text to get</a>
</li>
<li class="level1 nav-2-3"><a></a></li>
</ul>
</li>
I want to get text of those subcategories so I can later click on specific category by using text inside of a link element. My code is:
public Subcategory openSubcategory (String subcategoryName){
List<WebElement> subcategories = driver.findElements(By.cssSelector("a.level1"));
for (WebElement element: subcategories) {
if (element.getText().equals(subcategoryName)){
element.click();
break;
}
}
return new Subcategory(driver);
}
But it won't go inside loop, probably because element.getText() is empty.
To click on the WebElement with text as Shirts first you have to Mouse Hover the element with text as Men inducing WebDriverWait for the visibilityOfElementLocated and you can use the following locator strategies:
public Subcategory openSubcategory (String subcategoryName){
WebElement menuMen = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[contains(#class,'has-children') and text()='Men']")));
new Actions(driver).moveToElement(menuMen).build().perform();
List<WebElement> subcategories = driver.findElements(By.xpath("//a[contains(#class,'has-children') and text()='Men']//following::ul[1]//li/a"));
for (WebElement element: subcategories) {
if (element.getText().equals(subcategoryName)){
element.click();
break;
}
}
return new Subcategory(driver);
}
element.getText() can be empty.
Try:
element.getAttribute("value");
// or
element.getAttribute("innerHTML");
Change your CSS to be:
"a[class*='level']";
// or
"a[]";
Debug the code and check if the element is not null

Selenium: Can't scroll to click element that is not visible because of thread error: element is not visible

I am trying to click an element that is not visible and needs to be scrolled down to be visible. To fix this, I have tried to use javascript executor and action, but they do not work because before even scrolling, I get a thread error saying the element is not visible. I have made sure that the xpath to the element is correct and verified the code works with elements that are visible without the need to scroll.
<div class="product-grid-item clearfix" data-alpha="LOG ON T-SHIRT BLACK" data-price="4800" data-i="27">
<a href="/products/8r9ya45zmdwz" class="product-link">
<img src="[//cdn.shopify.com/s/files/1/0923/4190/products/Palace-2019-Autumn-T-Shirt-Log-On-black-1336\_200x200\_crop\_center#2x.jpg?v=1565334138](//cdn.shopify.com/s/files/1/0923/4190/products/Palace-2019-Autumn-T-Shirt-Log-On-black-1336_200x200_crop_center#2x.jpg?v=1565334138)" alt="LOG ON T-SHIRT BLACK" class="img">
</a>
<div class="product-info">
<a href="/products/8r9ya45zmdwz" class="product-link">
<h3 class="title">LOG ON T-SHIRT BLACK</h3>
</a>
<div class="price">
<span class="prod-price">$48</span>
</div>
</div>
</div>
I have tried javascript executor and action
WebElement element = driver.findElement(By.xpath("//*[#data-alpha='" + productName + "' and #class='product-grid-item clearfix']")); //error occurs at this line
int elementPosition = element.getLocation().getY();
String js = String.format("window.scroll(0, %s)", elementPosition);
((JavascriptExecutor)driver).executeScript(js);
element.click();
and
WebElement element = driver.findElement(By.xpath("//*[#data-alpha='" + productName + "' and #class='product-grid-item clearfix']")); //error occurs at this line
Actions builder = new Actions(driver);
builder.moveToElement(element);
builder.click();
builder.build().perform();
Error message:
no such element: Unable to locate element: {"method":"xpath","selector":"//*[#data-alpha='WINDOWLICKER HOOD GREY MARL' and #class='product-grid-item clearfix']"}
Try use WebDriverWait and change the locator with contains, may contain space.
WebDriverWait wait = new WebDriverWait(driver, 60);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[contains(#data-alpha,'" + productName.trim() + "') and #class='product-grid-item clearfix']")));
scroll here....
The element seems to be a dynamic element and as you mentioned that the element that is not visible and needs to be scrolled down to be visible so you can use either of the following solutions:
Using WebDriverWait and ExpectedConditions and elementToBeClickable():
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#class='product-grid-item clearfix' and contains(#data-alpha, 'LOG ON T-SHIRT BLACK')]//a[#class='product-link' and contains(#href, 'products')]/img[contains(#src, 'shopify')]"))).click();
Using WebDriverWait and ExpectedConditions and elementToBeClickable() through Actions:
new Actions(driver).moveToElement(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#class='product-grid-item clearfix' and contains(#data-alpha, 'LOG ON T-SHIRT BLACK')]//a[#class='product-link' and contains(#href, 'products')]/img[contains(#src, 'shopify')]")))).click().build().perform();

Element is not clickable at point - other element would receive the click

I have an element on a website which looks like below
<div id="wrapperCategory" class="categoryItemWrapper">
<div class="panel panel-default panel-categoryItem text-center categoryItem disabledItem" ng-class="category.CategoryStyleClass" ng-click="setselectedProduct(productIndex,product,category); setselectedProductAmount(null);" title="Category">
<div class="panel-heading">
Category
</div>
<div class="panel-body">
Price
</div>
<div class="panel-footer availability" ng-class="category.AvailabilityStyleClass">
<span ng-bind-html="category.AvailabilityText">Avail</span>
</div>
</div>
</div>
I need to click on it to get forward. If I manually click on each of these divs or on span website goes forward but SeleniumWebdriver can't click any of them.
I tried click on span and on div with ng-click event buch each time i get an error:
Exception in thread "main" org.openqa.selenium.WebDriverException: Element <div class="panel panel-default panel-categoryItem text-center categoryItem" ng-class="category.CategoryStyleClass" ng-click="setselectedProduct(productIndex,product,category); setselectedProductAmount(null);" title="Category"></div> is not clickable at point (619.2666625976562, 474.23333740234375). Other element would receive the click: <div style="top: 0;left: 0;bottom: 0;right: 0;position: fixed;pointer-events: auto !important;z-index: 10000;" id="cover-1526454140024"></div>
I don't get it.
Can I somehow check which element is clickable and which element overlaps this which I want to click (I dont'see any div with id="cover-1526454140024" in code of the website) ?
Updated:
Unfortunately it still doesn't work after your solutions.
The same exception when trying to click.
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
JavascriptExecutor js = (JavascriptExecutor) Mundial.driver;
js.executeScript("arguments[0].scrollIntoView();", categoryItem);
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(categoryItem));
categoryItem.click();
List<WebElement> selects = driver.findElements(By.tagName("select"));
Select ticketsToSelect = new Select(selects.get(3));
ticketsToSelect.selectByValue("number:2");
It only works in case when I put sleep and scroll down manually. I don't get it.
As per your response :
You will have to scroll down to let the web element available to your script.For that you can use this code :
public static void scrollDown(WebDriver driver, String YoffSet){
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript(YoffSet);
}
here you can call this method anywhere from your code.
Then you can use this code to interact with the web element :
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("static ID")));
element.click();
I experienced lot of such issues, as Ankur says, use wait before click
WebElement seems_unclickable = wait.until(ExpectedConditions.elementToBeClickable(By.id(...
One of the way is ExpectedConditions commands
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("Yourid")));
More examples can be found at http://toolsqa.com/selenium-webdriver/wait-commands/
Try "scrollIntoView".
public void ScrollElementIntoView(IWebElement element)
{
var js = driver as IJavaScriptExecutor;
js.ExecuteScript("arguments[0].scrollIntoView()", element);
}
I had the same issue and it was due to a having a non 100% zoom applied to the page body like:
body {
zoom: 90%;
}
Removing the css zoom fixed the issue.

How to open a WebElement from a Hoover Menu Selenium JAVA

Hello I'm new using selenium and I was trying to execute some tests from a web page.
This is my code:
System.setProperty("webdriver.gecko.driver","C:\\DRIVERS\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//Open Portal Fiscal
driver.get("http://150.23.110.111/Retenciones/");
//Find what field and enter the user and password
driver.findElement(By.id("frmLogin:txtUsr")).sendKeys("arrubio");
driver.findElement(By.id("frmLogin:txtPwd")).sendKeys("gnp00gnp");
driver.findElement(By.id("frmLogin:butLogin")).click();
Actions action = new Actions(driver);
WebElement we = driver.findElement(By.xpath(""));
action.moveToElement(we).moveToElement(driver.findElement(By.xpath("")));
I can enter to the page without problem and I can enter the user and the password to login, but there's a hoover menu on the next page that I can´t use and stops my automatic execution.
This is the xpath and the csspath:
xpath: /html/body/div[3]/div/div/form/div/ul/li[1]/ul/li[1]/a/span
csspath: html body div#content div#leftPanel.ui-layout-unit.ui-widget.ui-widget-content.ui-corner-all.ui-layout-west.blankBck div.ui-layout-unit-content.ui-widget-content form#j_id1833690111_27e067e8.blankBck div#j_id1833690111_27e067e8:j_id1833690111_27e0678e.ui-menu.ui-menubar.ui-widget.ui-widget-content.ui-corner-all.ui-helper-clearfix ul.ui-menu-list.ui-helper-reset li.ui-widget.ui-menuitem.ui-corner-all.ui-menu-parent.ui-menuitem-active ul.ui-widget-content.ui-menu-list.ui-corner-all.ui-helper-clearfix.ui-menu-child.ui-shadow li.ui-menuitem.ui-widget.ui-corner-all a.ui-menuitem-link.ui-corner-all span.ui-menuitem-text
And this is the element that appears inspecting the "Búsqueda" button.
<ul class="ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow" role="menu" style="display: block; height: auto; z-index: 1013; left: 0px; top: 28px;">
<li class="ui-menuitem ui-widget ui-corner-all" role="menuitem">
<a class="ui-menuitem-link ui-corner-all" href="/Retenciones/main/faces/m_evaPuntual.xhtml" style="width:120px" tabindex="-1">
<span class="ui-menuitem-text">Búsqueda</span>
</a>
</li>
<li class="ui-menuitem ui-widget ui-corner-all" role="menuitem">
</ul>
How can I select and open the button "Búsqueda" from the hoover menu?
Thanks for the attention :)
try using:
Actions action = new Actions(driver);
WebElement menu = driver.findElement(By.xpath("xpath for menu"));
WebElement item = driver.findElement(by.cssSelector("css selector values for Búsqueda"));
action.moveToElement(menu).moveToElement(item ).click().build().perform();
Try this below code using action class
WebElement menu_element = driver.findElement(By.xpath("your_menu_xpath"));
WebDriverWait wait = new WebDriverWait(driver, 10); //Explicit wait method, wait for web-element till 10 seconds so, your driver should able to find the web-element.
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("Your_submemu_xpath"))));
WebElement sub_menu_element = driver.findElement(By.xpath("Your_submemu_xpath"));
Actions action = new Actions(driver);
action.moveToElement(menu_element).moveToElement(sub_menu_element).click().build().perform();
Explanation:
1) First locate the menu element
2) Provide explicit wait method for few seconds so your driver may able to find the sub_menu_element that you want to go with.
3) After explicit wait locate the sub_menu element, that you want to go with.
4) Using Action class try to move element from menu to sub menu.

Getting child elements using WebDriver

I've got the following HTML code:
<div class="ui-selectmenu-menu" style="z-index: 1; top: 251px; left: 37px;">
<ul class="ui-widget ui-widget-content ui-selectmenu-menu-dropdown ui-corner-bottom" aria-hidden="true" role="listbox" aria-labelledby="gwt-uid-191-button" id="gwt-uid-191-menu" style="width: 270px; height: auto;" aria-disabled="false" aria-activedescendant="ui-selectmenu-item-999">
<li role="presentation" class="ui-selectmenu-item-selected">
All Applications</li>
<li role="presentation" class="">
Option Alpha</li>
<li role="presentation" class="ui-corner-bottom">
Option Beta</li>
</ul>
</div>
...
<div class="ui-selectmenu-menu"...>...</div>
I'm able to get the WebElement for ui-selectmenu-menu like this (there are many on the page; hence, the use of findElements) :
List<WebElement> dropdowns = driver.findElements(By.className("ui-selectmenu-menu"));
And the ul below it like this:
WebElement ddChild = dropdowns.get(0).findElement(By.className("ui-selectmenu-menu-dropdown"));
I'm even able to grab all the li under the ddChild like this:
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li[*]"));
But the problem that I can't seem to figure out how to grab the text-value of the <a href="#nogo"... tag under each li element.
I'd like to be able to loop through all the ddOpts and grab the <a href="#nogo"... text values and save them to an ArrayList<String>.
So, for example, my first ArrayList<String> value would contain All Applications, then Option Alpha, then Option Beta, and then jump to the next ul element from the next dropdowns and do the whole process again, all while adding to the ArrayList<String>.
I'm sure its a simple solution but I've got limited experience with Selenium WebDriver.
Thanks!
PS: Is there a simple way to grab the child of a WebElement?
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li/a"));
ArrayList<String> links = new ArrayList<String>();
for(WebElement we : ddOpts) {
links.add(we.getText();
}
To extract the href attribute of the WebElement (referring to the anchor tag <a> in this example, do this:
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li/a"));
ArrayList<String> links = new ArrayList<String>();
for(WebElement we : ddOpts) {
// ADD all the href attribute strings to the list
links.add(we.getAttribute("href"));
}
This may also solve your problem:
List<WebElement> dropdowns = driver.findElements(By.className("x-combo-list"));
WebElement ddChild = dropdowns.get(0).findElement(By.className("x-combo-list-inner"));
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id=\"x-auto-98\"]/div[4]"));
for(WebElement we:ddOpts){
System.out.println(we.getText());
if(we.getText().contains("ROLE_MANAGER")){
we.sendKeys("ROLE_MANAGER");
we.click();
break;
}
}
the below code will select the OptionAlpha in the dropdown of the above HTML code
driver.findElement(By.xpath("//*[#class='ui-selectmenu-menu')).click();
driver.findElement(By.xpath("//*[#class='ui-widget ui-widget-content ui-selectmenu-menu-dropdown ui-corner-bottom']//**[text()='Option Alpha']")).click();
Please try the below code to get all the links in the <a href
List<WebElement> allLis = driver.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li/a");
// Looping through above list using for-each loop
for(WebElement eachLi : allLis) {
System.out.println(eachLi.getText());
}
Hope this helps.
href="#nogo" is same for all the anchor tags, so it might create ambiguity in selecting the item by the method
dropdowns.findelement(By.linktext("#nogo"));

Categories

Resources