我试图从下拉列表中选择一个选项,只匹配一部分可见文本,因为整个文本不会总是是相同的。任何人都可以帮我解决这个问题吗?如何通过使用硒webdriver和java匹配文本模式从下拉列表中选择一个选项
回答
你可以使用下面的命令。让我知道它是否工作。
driver.findElement(By.id("id of the dropdown")).sendkeys("part of visible text");
driver.findElement(By.id("id of the dropdown")).sendKeys(Keys.ENTER);
我没有测试过这个,但这里是你如何在C#中完成它,你应该能够很容易地转换成Java代码。两种方法我能想到的:
1)
string selBoxID = "id of select box";
string partialText = "option text to match";
driver.FindElement(By.XPath("//select[@id='" + selBoxID + "']/option[contains(text(), '" + partialText + "')]")).Click();
OR
2)
SelectElement elSel = new SelectElement(driver.FindElement(By.Id("id of select box")));
IList<IWebElement> opts = elSel.Options;
foreach (IWebElement elOpt in opts)
{
if(elOpt.Text.Contains("partial text to look for"){
elOpt.Click();
return true;
}
}
return false;
+1,仅供参考,Java相当于“Select”类:https://code.google.com/p/selenium/source/browse/java/client/src/org/openqa/selenium/support/ ui/Select.java – Arran 2013-05-09 09:13:34
感谢您的帮助,它对我有用(选项1)。 – user2365105 2013-05-09 09:20:24
不客气! – ragamufin 2013-05-09 11:42:44
也许这是否行得通呢?
new Select(driver.findElement(By.id("MyIdOrOtherSelector"))).selectByVisibleText("Something");
虽然我不确定是否允许部分文本。 还有
selectByValue(value)
selectByIndex(index)
如果他们使用任何
下面是该
WebElement dropdown = driverObj.findElement(By.id(id));
dropdown.click();
List<WebElement> options = dropdown.findElements(By.tagName("option"));
for(WebElement option : options){
String optTxt = option.getText();
if(optTxt.contains(partialText)){
option.click();
break;
}
}
}
C#与LINQ一个java代码
var menuOptions = new SelectElement(Driver.FindElement({LocatorForMenu})).Options;
var requiredOption = menuOptions.FirstOrDefault(element => element.Text.Contains(partialTextToMatch));
if (requiredOption == null)
throw new Exception("Wasn't able to select menu item: " + partialTextToMatch);
requiredOption.Click();
非常感谢你对你的快速响应。这个问题是,我试图在这里找到的文本模式应该是起始文本。另外它不会从元素中释放焦点。 – user2365105 2013-05-09 09:04:49