Selenium - 如何从选项列表中选择选项? (只知道部分文本?)

时间:2012-01-10 22:16:14

标签: c# selenium automation automated-tests

选择部分匹配字符串的选项(如果不可能,我需要将所列选项的全名输入程序,以便可以选择)

Example if you want to select optionTQW 4493, you can just select with TQW?

<select id="_myselector" name="select-list">
<option value='1'>OptionZ 2345</option>
<option value='2'>optionTQW 4493</option>             
</select>

5 个答案:

答案 0 :(得分:2)

您可以使用XPath选择器:     //选择[@id ='_ myselector'] /选项[包含(。,'TQW')]

有关更具体的答案,了解您是否使用Selenium脚本语言与Selenium IDE或某种语言包装器(Java,python,ruby等)可能会有所帮助

答案 1 :(得分:1)

<tr>
    <td>select</td>
    <td>id=_myselector</td>
    <td>label=glob:option* 4493</td>
</tr>

答案 2 :(得分:1)

使用xpath选择器"//select[@id='_myselector']/option[contains(text(),'TQW')]"

答案 3 :(得分:0)

这是在ruby selenium webdriver中 -

@driver.find_element(:id, "_myselector").find_element(:css,"option[value='1']").click

答案 4 :(得分:-1)

您可以使用Selenium.Support.UI Namspace中的内置SelectElement

这是我创建的一个扩展方法来帮助解决这个问题。

public static void SelectOptionFromDropdown(this IWebDriver driver,IWebElement dropdown, SelectBy selectBy, string item)
    {
        switch (selectBy)
        {
            case SelectBy.Index:
                int index;
                if (Int32.TryParse(item, out index))
                {
                    new SelectElement(dropdown).SelectByIndex(index);
                }
                else
                {
                    ExceptionHandler.LogException("Unable to Convert String To Int", "WebdriverExtension", "SelectOptionFromDropdown");
                    throw new Exception();
                }

                break;

            case SelectBy.Text:
                new SelectElement(dropdown).SelectByText(item);
                break;
            case SelectBy.Value:
                new SelectElement(dropdown).SelectByValue(item);
                break;
        }
    }

我只是重新阅读你的帖子,你想选择部分字符串匹配,我不知道如何做到这一点,并且更喜欢使用更严格的方法。所以我倾向于使用Index或Value。

但希望这有助于指明你正确的方向。