Selenium WebDriver: The challenge of using visibilityOfElementLocated when the element is not actually visible

I've encountered an issue with the Firefox Webdriver where it fails to accurately determine if an element is visible. Here is the code I am using, which incorrectly indicates that the element is visible:

wait.ignoring(UnhandledAlertException.class).until(ExpectedConditions.visibilityOfElementLocated(By.id("ad")));

Now, what happens when testing a website in situations where an element may be present in the site's source but not actually visible (due to another element blocking it, for example). It seems like the visibilityOfElementLocated method only checks if the element's width and height are greater than 0. Is there a way to verify if the element is truly visible to a user browsing the site, taking into account issues like poor layout and incorrect z-indexes? That would be extremely helpful...

Thank you!

Answer №1

Have you considered the possibility that you may be mistakenly testing for presenceOfElementLocated rather than visibilityOfElementLocated? The visibilityOfElementLocated function only works if the element being searched for has its display CSS attribute set. Some individuals try to determine if an element exists by using ".findElements(By).size() > 0", but here is an alternative approach that involves exception handling.

While it may seem excessive, one option is to create your own visibility function. In this instance, I have named it "elementExists()". This function checks for the presence of an element and then manages any visibility-related exceptions that may arise:

public boolean elementExists( By locator ) {   
    WebElement foo = null;
    try {
        foo = this.getElementByLocator( locator, 10 );
     } catch ( TimeoutException te) {
        System.out.println("A timeout occurred while searching for the element: " + 
            locator.toString() );
        //Swallow exception: ExceptionUtils.getMessage(te);
        return false;
    } catch ( ElementNotVisibleException env ) {
        System.out.println("The element was found, but it is not visible: " +
            locator.toString() );
        //Swallow exception: ExceptionUtils.getMessage(env);
        return false;
    }
    if ( foo == null ) {
        return false;
    } else {
        return true;
    }
}

public WebElement getElementByLocator( By locator, int timeout ) {
    System.out.println("Calling method getElementByLocator: " + 
        locator.toString() );
    int interval = 5;
    if ( timeout <= 20 ) interval = 3;
    if ( timeout <= 10 ) interval = 2;
    if ( timeout <= 4 ) interval = 1;
    Wait<WebDriver> wait = new FluentWait<WebDriver>( se.myDriver )
        .withTimeout(timeout, TimeUnit.SECONDS)
        .pollingEvery(interval, TimeUnit.SECONDS)
        .ignoring( NoSuchElementException.class, 
                       StaleElementReferenceException.class );
    WebElement we = wait.until( ExpectedConditions
           .presenceOfElementLocated( locator ) );
    return we;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on Incorporating CSS in import.io Connect Extract

By utilizing the import.io connector, I successfully extracted a portion of HTML from the source website. The output was returned as "html" type, consisting of a single table of data with styles defined in the body HTML but not fully extracted. Consequentl ...

Utilizing jQuery to highlight and customize portfolio items with odd numbers

I'm currently trying to rearrange the module header and portfolio image for odd-numbered portfolio items. Feel free to check out my sandbox here. I thought the code below might do the trick, but it's a no-go. jQuery(document).ready(function($){ ...

Using jQuery to close a DIV with a delay

At the top of my website, I have set up an alert with a close button. The jQuery function for closing the alert is as follows: /* CLOSE ALERT BAR WITH BUTTON */ $('a.ctp-alert').click(function () { $("div.ctp-alert").slideUp(); }); While this f ...

Which is better for my selenium project - ANT or MAVEN?

In my current project, I am in the process of creating a hybrid framework for GUI automation, and I have decided to use TestNG. However, I am now faced with the decision of whether to go with ANT or MAVEN for build management. While I have researched and ...

Leverage the power of Bootstrap by incorporating not one, but two carousels on a single page - one featuring a single item per

I have a unique challenge with using multiple Bootstrap Carousels on my WordPress website One of the carousels features one item per slide, while the other carousel has three items per slide, moving one item at a time in a cyclical pattern like this: [1, ...

The cascading style sheet used by a lightbox

I constructed a lightbox using the following HTML code: <a id="show-panel" href="#">Show Panel</a> <div id="lightbox-panel"> <h2>Lightbox Panel</h2> <p>You can add any valid content here.</p> <p align="center" ...

What is the method for selecting a particular button on a webpage with Selenium when only the button's name is visible in the HTML code?

There are three identical buttons named 'continue' on a webpage. None of the buttons have an id in their HTML code. My objective is to click on the second button without resorting to using an xpath locator. ...

Leverage the power of HTML, CSS, and Bootstrap within Visual Studio 2022 when developing with

Could someone help me figure out how to implement HTML, CSS, and JavaScript design in Visual Studio 2022 while utilizing ASP.NET controls for coding purposes? I am encountering difficulties in starting my work on a website project. Any assistance would be ...

How can I incorporate multiple JSX files into plain HTML without using npm?

I have a question regarding importing JSX files in an HTML file without using npm and directly running it with LiveServer. I have two files, index.js and app.jsx, that I want to connect within my index.html script. How can I achieve this? Code: index.html ...

The playwright instructed to capture a screenshot following each click

I am a beginner when it comes to using Playwright. I was optimistic that I could achieve my goal using page.evaluate, as in the documentation it states "page.evaluate() API can run a JavaScript function in the context of the web page and bring results back ...

Switch the dropdown selection depending on the checkbox status

I'm currently facing a bit of confusion with my project. I am constrained by an existing framework and need to come up with a workaround. To simplify, I am tasked with populating a dropdown list based on the selected checkboxes. I have managed to get ...

Show concealed content for individuals who do not have javascript enabled

One of the challenges I faced was creating a form with a hidden div section that only appears when a specific element is selected from a list. To achieve this, I utilized CSS to set the display property of the div to 'none' and then used jQuery t ...

Efficiently Displaying Multiple HTML Elements in React Native WebView

I am currently working on developing an Epub reader in React Native and facing a challenge. I need to find a way to efficiently transfer multiple html content files from the Epub container to the webview in order to achieve seamless pagination. ...

Animation of underline on hover for NavLink

As a newcomer to React, I am currently exploring how to create an animated underline effect when hovering over a NavLink from reactstrap. I have managed to get the underline working on hover thanks to the solution provided at , but I am struggling with imp ...

Looking to add tiered custom attribute select boxes in SnipCart - how can I make it happen?

I am interested in implementing two custom attributes for products, where the options for the second custom attribute are determined by the selection of the first attribute. My specific situation involves selling art in various formats and sizes, with dif ...

The data type '{}' cannot be assigned to the type 'WebElement'

Background: I am in the process of updating the end-to-end tests to utilize async/await functionality. However, when attempting to modify the function (with a return type promise.Promise < WebElement>) to be asynchronous and calling it from the test, ...

Struggling to troubleshoot this issue with Python Selenium Chromedriver. Help needed!

from selenium import webdriver from selenium.webdriver.common.keys import Keys import os Game_Pin = input('Please input your PIN: ') NickNAME = input('Please input your nickname: ') def Enter_Press(): browser.find_element_by_name( ...

Updating Button Text with PHP on WooCommerce

Hi there, I'm trying to find a way to translate a button in my WooCommerce store without using LocoTranslate or any other tools. Is there a PHP function that can help me change the button text without needing an ID? If you want to take a look at the ...

Tips for interacting with a non-existent button using Selenium and browser.page_source

I am having trouble finding the button Alle akzeptieren to click. Even after searching through the print(browser.page_source), I cannot locate it. Utilizing a WebDriverWait(browser, 10) did not provide a solution. This is my code snippet: browser = webdri ...

Revealing the Contents of a View Selection in an HTML DIV

By setting my DIV to contenteditable = true, I am able to capture images from the clipboard. After pasting the image, I can view the base64 value by right-clicking and selecting View Selection Source. Copying and saving this base64 value allows me to see t ...