Search code examples
htmlcssselenium-webdriverxpathcss-selectors

Problem with obtaining title of a tooltip in selenium webdriver


I am trying to find a way to obtain a title of a tooltip displayed on mouse over event on a page: https://demo.nopcommerce.com/nike-floral-roshe-customized-running-shoes

This tooltip appears when mouse is over 2 of "Print" items. It is about header of this tooltip:

//*[@id="image-squares-8"]/li[1]/div/div[1]

//*[@id="image-squares-8"]/li[2]/div/div[1]

Natural

Fresh

How to get it programmaticaly in selenium webdriver?

I have such code:

        mainPage = mainPage.moveToApparel()
                .select()
                .selectNthProductOnPage(1) -- moves to above page
                .selectSize(8)  -- select size of shoes
                .selectColor("White/Black") -- select color on this page
                .moveToStyle(1); -- action.moveToElement(element);

        String text = mainPage.getStyleTooltip();  -- returns empty string!?
    public String getStyleTooltip() {
        // tooltip-header
        return tooltipHeader.getText();
    }
    @FindBy(css = "div[class='tooltip-header']")
    @CacheLookup
    WebElement tooltipHeader;

in this code

mainPage.getStyleTooltip();

returns empty string, not current tooltip text. How to obtain current tooltip text in this case?

BR,

fotrenc


Solution

  • Your tooltip is hidden when you are getting it's text.

    getText() function returns text only for elements that are visible.

    To get text from invisible element you can get element innerHTML attribute.

    public String getStyleTooltip() {
         return tooltipHeader.getAttribute("innerHTML");
     }
    

    if you need to get current visible tooltip, you should hover it first and then filter elements from list and get first visible, smth like

    @FindBy(css = "div[class='tooltip-header']")
    @CacheLookup
    List<WebElement> tooltipHeaders;
    
    public String getStyleTooltip() {
         return Stream.of(tooltipHeaders)
                    .filter(el -> ((WebElement) el).isDisplayed())
                    .findFirst().map(el -> ((WebElement) el).getAttribute("innerHTML")).orElse("");
     }