1

I can't seem to get the correct XPath syntax to find this select element that has a dynamic start to the ID field but ends with static data.

<select name="" autocomplete="off" id="edlbpDesktopFfqp_B005WJQUJ4-predefinedQuantitiesDropdown" tabindex="-1" class="a-native-dropdown">
                        <option value="1" selected="">
                            1
                        </option>
                        <option value="2">
                            2
                        </option>
                        <option value="3">
                            3
                        </option>
                        <option value="4">
                            4
                        </option>
                </select>

I've tried both of these unsuccessfully:

var dd = driver.FindElement(By.XPath("//*[ends-with(@id,'predefinedQuantitiesDropdown')]"));
dd.Click();

AND

var dd = driver.FindElement(By.XPath("//*[contains(@id, 'predefinedQuantitiesDropdown')]"));
dd.Click();

Your help would be greatly appreciated.

DebanjanB
  • 118,661
  • 30
  • 168
  • 217
Roro
  • 321
  • 1
  • 17

2 Answers2

1

The ends-with XPath Constraint Function is part of XPath v2.0 but as per the current implementation Selenium supports XPath v1.0.

You can find a detailed discussion in How to find element based on what its value ends with in Selenium?

As the element is a dynamic element to Click() on the desired element you have to induce WebDriverWait for the desired ElementToBeClickable and you can use either of the following Locator Strategies as solutions:

  • CssSelector:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("select.a-native-dropdown[id$='predefinedQuantitiesDropdown']"))).Click();
    
  • XPath:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//select[@class='a-native-dropdown' and contains(@id, 'predefinedQuantitiesDropdown')]"))).Click();
    

Note:However as per the best practices as the desired element is a <select> tag, so ideally you need to use the SelectElement Class and it's methods from OpenQA.Selenium.Support.UI namespace to select any option.

DebanjanB
  • 118,661
  • 30
  • 168
  • 217
0

You should use Select class to select item from drop down.You can try any of the below method.Hope this helps.

import org.openqa.selenium.support.ui.Select;



 Select select=new Select(driver.findElement(By.xpath("//select[contains(@id ,'predefinedQuantitiesDropdown')]")));

   select.selectByVisibleText("1"); //text visible on drop down
   select.selectByValue("1");     //value attribute on option tag
   select.selectByIndex(1);       //Index 1,2....n
KunduK
  • 26,790
  • 2
  • 10
  • 32