使用SelectByText(部分)与C#Selenium WebDriver绑定似乎不起作用

问题描述 投票:6回答:2

我在C#中使用Selenium WebDriver Extensions通过部分文本值从选择列表中选择一个值(实际前面有一个空格)。我无法使用部分文本匹配来使其工作。我做错了什么或这是一个错误?

可重复的例子:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;

namespace AutomatedTests
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://code.google.com/p/selenium/downloads/list");
            var selectList = new SelectElement(driver.FindElement(By.Id("can")));
            selectList.SelectByText("Featured downloads");
            Assert.AreEqual(" Featured downloads", selectList.SelectedOption.Text);
            selectList.SelectByValue("4");
            Assert.AreEqual("Deprecated downloads", selectList.SelectedOption.Text);
            driver.Quit();
        }
    }
}

提供错误:OpenQA.Selenium.NoSuchElementException: Cannot locate element with text: Featured downloads

c# .net selenium webdriver selenium-webdriver
2个回答
8
投票

SelectByText方法已被破坏,因此我编写了自己的名为SelectBySubText的扩展方法来执行它的目的。

using System.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

namespace AutomatedTests.Extensions
{
    public static class WebElementExtensions
    {
        public static void SelectBySubText(this SelectElement me, string subText)
        {
            foreach (var option in me.Options.Where(option => option.Text.Contains(subText)))
            {
                option.Click();
                return;
            }
            me.SelectByText(subText);
        }
    }

0
投票

如果您可以在简单的HTML页面中重现问题,那么您一定要提交错误报告。

看看source code SelectByText首先这样做:

FindElements(By.XPath(".//option[normalize-space(.) = " + EscapeQuotes(text) + "]"))

如果它没有找到任何东西,那么这样做:

string substringWithoutSpace = GetLongestSubstringWithoutSpace(text);
FindElements(By.XPath(".//option[contains(., " + EscapeQuotes(substringWithoutSpace) + ")]"))

所以在理论上它应该有效。您也可以自己使用XPath,看看是否可以在您的情况下使用它。

© www.soinside.com 2019 - 2024. All rights reserved.