-1

When I execute my script using IEDriver without compatibility view, my test script is running without any problem.

But, If I execute the same script after adding domain in compatibility view, then some elements are not found and I'm getting exceptions.

e.g. I want to get text of selected item from this DOM:

<select id="selectNumber" name="selectNumber" style="width:180px;">
    <option selected="selected" value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

and I'm using XPath .//*[@id='selectNumber']/option[@selected='selected'] to get text but it does not work.

I just checked that in IE DOM selected="selected" is not displayed for selected option until I change Document version manually.

Tom
  • 1,387
  • 3
  • 19
  • 30
Devang
  • 365
  • 2
  • 6
  • 26
  • Most likely you're using the compatibility view to run your tests as an older version of Internet Explorer and the `selected` attribute in this case may not be supported. One way to fix this in general would be be trying changing the xpath to use ids, classes even if you may need to include some upper nodes too. In your case to use the value for the option node. – Cosmin Oct 04 '16 at 10:33

2 Answers2

2

You can use the Select class that works with every browser. Here's some code

Select sel = new Select(driver.findElement(By.id("selectNumber")));
WebElement selectOption = sel.getFirstSelectedOption();
String text = selectOption.getText();
JeffC
  • 22,180
  • 5
  • 32
  • 55
0

I think you should consider to change from using XPath to use cssSelector. It's much safer to find the elements, not depending on the whole "path". There's a big chance it would not break when using cssSelector running with IEDriver (as you stated in your question).

You can achieve the same goal with both, but when you use XPath, your DOM is much more sensible to changes, and you have bigger chances to see tests broken after page changes.

For your case, you could use it in two ways:

XPath (as you must have it)

  1. driver.findElement(By.xpath(".//*[@id='selectNumber']/option[@selected='selected']"))

Selector

  1. driver.findElement(By.cssSelector("#selectNumber[selected]"))

When you have more complex "paths" you can combine more things like CSS classes in cssSelectors. For example (when you don't have ID):

<select class"nice-dropdown" name="selectNumber" style="width:180px;">
    <option selected="selected" value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

driver.findElement(By.cssSelector("select.nice-dropdown")) (return the select element) driver.findElement(By.cssSelector("select.nice-dropdown option[value='3']")) (return the option with value=3)

With selectors you have shorter "paths". They work in the same way as selectors are used in CSS.

As reference:

Hope this information is somehow helpful.

Tom
  • 1,387
  • 3
  • 19
  • 30