What's the correct XPath syntax to check if an option
element is currently selected, or just to get the selected option
element from a select
element, on an open page with which the user, and JavaScript, may have interacted? Is this even possible with XPath, or does it lack the ability to look at DOM properties?
I can't find any documentation on this, and have (speculatively) tried:
//option[@selected=true]
//option[@selected="selected"]
//option[@selected]
but none of these work; they simply don't match any elements.
(In case it matters, I've tried this both using the $x
function in the Chrome developer console, and using the find_elements_by_xpath
method in Selenium for Python.)
Short answer: it's not possible.
Longer answer: XPath can look at HTML attributes, but it can't look at DOM properties. Selecting an <option>
element in a <select>
changes the selected
property of the <option>
to true
, and also changes the value
property of its parent <select>
element, but it doesn't affect the attributes of either, so it is invisible to XPath.
To find <option>
elements that have the selected
attribute set, which is often how a page author might determine which option is initially selected, you can use //option[@selected]
. But this does not find the currently selected <option>
; changes that the user makes to the selection are invisible to XPath. There's no guarantee it will even find the initially selected option, since it's possible that the page author didn't put the selected
attribute on any elements and either let the browser select the first option by default or had some JavaScript select the initial option via the selected
property.
The multiple other answers here claiming that a selector like //option[@selected]
can detect selection changes made by the user after the page loads are simply completely wrong.
Of course, if you're able to use CSS selectors instead of XPath selectors, then option:checked
will do the job.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With