如何通过 C# 使用 XPath ends-with 识别带有动态 ID 的 select 标签

How to identify the select tag with dynamic ID using XPath ends-with through C#

我似乎无法获得正确的 XPath 语法来找到此 select 元素,该元素具有 ID 字段的动态开头但以静态数据结尾。

<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>

我试过这两个都不成功:

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

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

非常感谢您的帮助。

ends-with XPath Constraint FunctionXPath v2.0 的一部分,但根据当前的实现 Selenium 支持 XPath v1.0.

您可以在

中找到详细的讨论

由于该元素是 Click() 所需元素上的动态元素,因此您必须为所需的 ElementToBeClickable[=44= 引入 WebDriverWait ] 并且您可以使用以下任一方法 作为解决方案:

  • 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();
    

注意:但是根据最佳实践,因为所需的元素是<select>标签,所以理想情况下你需要将 SelectElement Class and it's methods from OpenQA.Selenium.Support.UI 命名空间用于 select 任何选项。

您应该使用 Select class 到 select 掉落的物品 down.You 可以尝试以下任何一项 method.Hope 这会有所帮助。

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