无宽高的可见元素是否存在?Selenium交互校验逻辑疑问
offsetWidth/offsetHeight and isDisplayed() for Element Interactivity in Selenium? Great question! At first glance, it seems like if element.isDisplayed() returns true, the element should naturally have positive width and height. But real-world web rendering has edge cases where an element can be "displayed" (per Selenium's check) but take up no physical space on the page—this is exactly why that extra width/height validation exists.
Let’s break down the code you shared first:
public boolean isElementInteractable(WebElement element) { JavascriptExecutor js = (JavascriptExecutor) driver; String offsetWidth = js.executeScript("return arguments[0].offsetWidth;", element).toString(); String offsetHeight = js.executeScript("return arguments[0].offsetHeight;", element).toString(); if ((Integer.parseInt(offsetWidth) != 0 && Integer.parseInt(offsetHeight) != 0) && element.isDisplayed()) { return true; } return false; }
Its core logic is: an element is only considered interactable if it’s not marked as hidden by CSS/HTML rules AND actually occupies visible space on the page.
Here are the key edge cases that justify this extra check:
Empty or content-collapsed elements
Imagine an empty<span>or<div>with no text, no padding, no borders, and CSS that forces its dimensions to zero (likeline-height: 0orfont-size: 0). Selenium’sisDisplayed()will returntruebecause the element isn’t hidden withdisplay: noneorvisibility: hidden, but itsoffsetWidthandoffsetHeightwill be 0. Trying to click such an element does nothing—there’s no physical area to interact with.Dynamic elements in a loading state
For elements that load content asynchronously (e.g., a placeholder div waiting for an image or API data to load),isDisplayed()might returntrueas soon as the element is added to the DOM, but its width/height will stay 0 until the content loads. Attempting to interact with it before that fails, so checking for positive dimensions ensures the element is fully rendered and ready.Zero-dimension form elements
Some form elements (like inputs styled to be "visible" but withwidth: 0; height: 0for styling hacks) will passisDisplayed()but have no clickable area. The width/height check catches these cases before you waste time trying to interact with them.Elements clipped entirely by parent containers
If an element has defined dimensions but is pushed completely outside a parent container withoverflow: hidden,isDisplayed()may still returntrue(since the element itself isn’t hidden). But the element has no visible presence on the page, so the width/height check ensures you don’t treat it as interactable.
In short: isDisplayed() only verifies that the element isn’t explicitly hidden by the browser’s visibility rules. It doesn’t confirm that the element has any actual space you can interact with. The offsetWidth/offsetHeight check fills that gap, making your interactability check far more robust.
内容的提问来源于stack exchange,提问作者Alpha

