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