繁体   English   中英

如何通过 C# 使用 XPath 以动态 ID 识别带有动态 ID 的选择标记

[英]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

您可以在如何根据元素在 Selenium 中的值结尾找到元素中找到详细的讨论

由于该元素是所需元素上Click()的动态元素,因此您必须为所需的ElementToBeClickable引入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类及其来自OpenQA.Selenium.Support.UI命名空间的方法来选择任何选项。

您应该使用Select类从下拉列表中选择项目。您可以尝试以下任何一种方法。希望这会有所帮助。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM