eastwater
eastwater

Reputation: 5572

Selenium java: how to know which DOM element is pointed by a WebElement?

Selenium java: how to know which DOM element is pointed by a WebElement from java debugger and browser developer tool?

Sometimes the selector is very complex, consisting of both xpath and css Selector and it is very helpful to know which DOM element is pointed during debugging.

WebElement
    ------> show me the element in DOM

Browser developer tools does not support mixed selectors. For example,

WebElement foo = driver.findElement(By.xpath("//div[@id='foo'][./ancestor::span]"));
WebElement helloWorld = foo.findElement(By.cssSelector(".hello .world"));
WebElement oops = helloWorld.findElement(By.xpath(".//li[1]"));

In the real world, this can get very complicated.

Upvotes: 0

Views: 354

Answers (1)

S A
S A

Reputation: 1865

TL;DR, You need to understand how selectors work. You can visit the links of the references for css selector and xpath.

Now let's look at the three elements and their selectors and how they locate an element.

  • The foo element is an element who has the id foo and also has an ancestor span node. Though ids should be a unique identifier and it shouldn't need any more axes to identify in a document.
  • Then HelloWorld element. You are searching inside the foo element. It will disregard all other matching elements and only find the child element of the foo element. In your sample code, you've put space between the two class in the CSS selector. It would mean that there is an element with class hello and there is a child element inside that element with class world. But if you remove the space then it means that there is an element with both class hello and world. Which can be easily interpreted to an XPath "//*[contains(@class, 'hello')][contains(@class, 'world')]"and you could use this XPath to make the one XPath to directly to find this element with one locator instead of two.
  • Now the oops element is easy to understand. It is the first li tag inside the HelloWorld element.

To find the element, You can first use the first selector in the browser's dev tool then find the next element inside the first element using the second selector and so on. Dev tools show the hierarchy of the elements so that can be done easily.

Upvotes: 0

Related Questions