L
L
LaFable2019-08-13 10:58:21
selenium
LaFable, 2019-08-13 10:58:21

Why is Selenium finding an element that isn't there?

Good afternoon!
Recently started working with Selenium.
An interesting situation has arisen, perhaps someone can explain how this happens and how to avoid it.
The user's full name is displayed on the site
5d526ae879bbe892607745.gif
In the profile settings, it is possible to hide the full name. The element disappears from the DOM, not just the style is set for the element that it is hidden, but it disappears.
5d526b630839e612714819.gif
In the test, you need to check that the element really does not exist.
And now the most interesting. Below is a method that checks for the presence of an element in two different ways.
In the first case, using FindsBy, he writes that the element is not equal to NULL, and in the second case he writes that it is (respectively, the second case is correct). The question is why the first case does not return NULL, and what to do about it)

internal void IsHiddenUsername()
        {
            if (UserName != null)
            {
                //
            }

            if (Username() != null)
            {
                //
            }
        }

        [FindsBy(How = How.ClassName, Using = "account-widget__username")]
        internal IWebElement UserName;

        private IWebElement Username()
        {
            try
            {
                IWebElement element = driver.FindElement(By.ClassName("account-widget__username"));
                return element;
            }
            catch 
            {
                return null;
            }
        }

Here is what is returned in the first if (this is not the element itself, but something else):
5d526cfea6269390280926.png
At the same time, naturally, when trying to return, for example, the text UserName.Text, NoSuchElementException falls out

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
ScriptKiddo, 2019-08-13
@ScriptKiddo

1. Install Xpath Helper
2. Search for elements by query
3. Come up with another Xpath that would explicitly point to the desired element, such as

//div[@class='account-widget']//div[@class='account-widget__username']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question