I'm writing some tests in java for a webpage with selenium. I see a lot of methods to ensure that an element is present on the page. But my need is to check that an element is not present on the page. More precisely, I need to check that the user has closed the pop up.
For the moment I see only methods to check that an element is present on thepage and not the contrary, like
WebElement element = driver.findElement(By.name("q"));
Do you know if methods exists to to check that an element is not present on the page ?
Thanks
I don't think there is some method which checks if an element is present.
However, you could do
List<WebElement> list = driver.findElements(By.name("q"));
if(list.size()==0)
System.out.println("Not Present")
#findElements returns a list containing the matching WebElements.
You can also try following:
public boolean isElementPresent(WebElement element){
try{
element;
return true;
//element is present
}
catch(Exception e){
return false;
//element not present
}
}
Related
As Java is not my "best language" I would like to ask for support. I'm trying to validate if element from the list contains a specific value.
I'm having element which locates at least 5+ elements
I'm trying to get that element:
eg. List<WebElement> elementsList = getWebElementList(target, false);
I'm trying to validate if specific text is a part of the taken list. By doing something like:
elementsList.contains(valueToCheck);
it does not work...
also I found a way of using stream() method which looks more/less like this but I'm having troubles with continuation:
elementsList.stream().filter(WebElement::getText.....
Can you please explain me how lists are handled in Java in modern/ nowadays way? In C# I was mostly using LINQ but don't know if Java has similar functionality.
Once you get the element list.You can try something like that. this will return true or false.
elementsList.stream().anyMatch(e -> e.getText().trim().contains("specficelementtext")
You can not apply contains() method directly on a list of WebElement objects.
This method can be applied on String object only.
You also can not extract text directly from list of WebElement objects.
What you can do is:
Get the list of WebElements matching the given locator, iterate over the WebElements in the list extracting their text contents and checking if that text content contains the desired text, as following:
public static boolean waitForTextInElementList(WebDriver driver, By locator, String expectedText, int timeout) {
try {
List<WebElement> list;
for (int i = 0; i < timeout; i++) {
list = driver.findElements(locator);
for (WebElement element : list) {
if (element.getText().contains(expectedText)) {
return true;
}
}
i++;
}
} catch (Exception e) {
ConsoleLogger.error("Could not find the expected text " + expectedText + " on specified element list" + e.getMessage());
}
return false;
}
I am writing a web spider for a site on the public internet - that is, I can't control the site that is the target. For some reason certain elements I am interested in change their name, id and similar between reloads.
Since Selenium, AFAIK, doesn't have a method that returns true/false if an element exists or not (instead it throws exceptions), what is a good strategy to handle this situation?
In pseudo code
if element A exists click A
else if element B exists click B
else if element C exists click C
Currently I have to surround every if with a try/catch.
Does Selenium have something built in for this purpose or should I write my own helper method?
public Boolean elementExists(WebDriver driver, String xpath) {
// this will not throw any exception, if no element is found, the list will be empty
List<WebElement> elements = driver.findElements(By.xpath(xpath));
if (elements.size() > 0) {
return true;
}
else {
return false;
}
}
Any locator can be interpreted with xpath.
For id "foo" the xpath will be "//*[#id = 'foo']"
For name "foo" the xpath will be "//*[#name = 'foo']"
etc
I got a problem and I don't know how to solve it right. Situation: user enters login and password, and then he could be at one of two pages.
Question is: how to check correctly in which page we are?
1. I want to use WebDriverWait, so my implicitlyWait = 0 ms,
2. I use Page Object pattern, pages were initialized with AjaxElementLocatorFactory
a. So, if I'll do method for check some element like this:
#FindBy(id = "pushOutMessage")
private WebElement messageText;
public boolean pageIsPresent() {
return messageText.isDisplayed();
}
It will be not right because if page is wrong, then WebDriver will wait N seconds for this element. So it makes my simple tests slow, very-very slow.
b. If I will check element with "findElement" - my implicity waits is 0 ms, so if element was slowly-loaded pageIsPresent returns false, even if page is right.
I hope there is some other way to do this. Need your help!
There are multiple ways you can do that. but the easiest way will be to check the elemenet counts
I would rather do
#FindBy(id = "pushOutMessage")
private List<WebElement> elements;
public int pageIsPresent() {
return elements.size();
}
And, somewhere test the pageIsPresent() is 0 or greater. if greater than 0 we know the page element was returned
And, since you are using pageobject pattern and Java I would recommand you to create an overloading to the baseClass which will check for a selector everytime you instantiate a new pageobject. I have a git repo here with TestNG. that might help
After the user enters or clicks submit or login button you can do something like this:
public Object clickLogin() {
loginElement.click();
try{
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementedLocatedBy(By.id("pushOutMessage")));
return PageFactory.initElements(driver, FirstPage.class);
} catch (TimeoutException te) {
return PageFactory.initElements(driver, SecondPage.class);
}
}
public static WebElement drpdwn_selectMonth() throws Exception{
try{
WebElement monthSelector = driver.findElement(By.id("monthID"));
monthSelector.click();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
monthSelector = driver.findElement(By.xpath("//*[#id='monthID']/option[2]"));
monthSelector.click();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}catch (Exception e){
throw(e);
}
return element;
}
how to do a Boolean check there is a value under drop down list is selected?
how to print and get the value selected in drop down list
According to your given little details , It can be done in below way :
WebElement monthSelector = driver.findElement(By.id("monthID"));
monthSelector.click();
if(monthSelector.isSelected())
{
Select sel = new Select(driver.findElement(By.id("monthID")));
sel.selectByVisibleText("Your-dropdown-value");
}
else
{
System.out.println("Sorry , Dropdown not selected yet");
}
Please replace Your-dropdown-value with your dropdown actual value e.g "January".
Better you also share your HTML code , if above does not work for you.
HTML snip would help, but here's my take. If your menu element is a <select> element, you can make use of the Select API.
Once instantiated with your WebElement representing the root locator of the menu, you can use the getAllSelectedOptions() or getFirstSelectedOption() methods to retrieve the text of the selected option(s). From here, you can print the value, or validate the selected option in your assert statement.
This is only high level concept, but if you read through the API Doc, you should be able to come up with the solution that fits your needs.
I just want to check if the element is present on the page or not?
I am confused with what can be used. What is feasible to use isDisplayed() or isPresent()?
What is the difference between these two?
There is no isPresent function
The isDisplayed returns True only if the element is displayed on the webpage and is actually visible.
If you just want to check if the element is present then you can do one of the following:
Put the code for findElement inside a try/catch block. If it goes inside catch with NoSuchElementException then the element is not present.
Do findElements instead of findElement and if length of the list returned by findElements is zero, then the element is not present.
In both the cases you need to make sure that you are finding the desired element using a unique selector.
to simplify.. I've posted code below
public static boolean isElementPresent(final WebDriver driver, By by) {
try {
waitForElement(driver, by, 2);
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}