我似乎无法获得正确的XPath语法来找到这个选择元素,该元素具有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 Function是XPath v2.0的一部分,但根据目前的实现,Selenium支持XPath v1.0。
你可以在How to find element based on what its value ends with in Selenium?找到详细的讨论
由于元素是所需元素上Click()
的动态元素,因此您必须为所需的ElementToBeClickable引入WebDriverWait,并且您可以使用以下任一Locator Strategies作为解决方案:
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