Find CURRENTLY selected

后端 未结 4 1120
醉话见心
醉话见心 2021-01-04 06:42

What\'s the correct XPath syntax to check if an option element is currently selected, or just to get the selected option

相关标签:
4条回答
  • 2021-01-04 07:05

    I think we can use a knowledge from @Mark's answer and account that. Let's just find a node which HAS desired attribute:

    tree.xpath('//select/option[@selected]/text()')[0].strip()
    
    0 讨论(0)
  • 2021-01-04 07:10

    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.

    0 讨论(0)
  • 2021-01-04 07:11

    The problem could be the " (double quotes).

    //select/option[@selected='selected'] - Will match the selected option, i am using this successfully.

    //select/option[@selected='selected' and @value='specific value'] - Will only match the selected option if it has a 'specific value', i'm also using this.

    If you are still having trouble, it could be an entirely different problem, perhaps there is no option node. I hope this helps.

    0 讨论(0)
  • 2021-01-04 07:20

    I would try //option[@selected='true']

    i.e. driver.findElements(By.xpath("//option[@selected='true']")).getText();

    0 讨论(0)
提交回复
热议问题