Skip to main content
 首页 » 编程设计

c#之使用变量作为选择器与 Selenium 2 Webdriver by.cssselector

2024年02月23日35luoye11

我正在使用 Visual Studio 2010 在 C# 中编写 Selenium 2 Webdriver 自动化测试。 我到处搜索使用变量作为选择器的示例,但没有找到任何有效的方法。我发现的一个用作选择器的变量示例具有带 $ 前缀并包含在 {} 中的变量。 下面是我正在尝试做的一个例子:

string surveyName = "Selenium test survey"; 
Driver.FindElement(By.CssSelector("tr[svd='${surveyName}']")) 

我得到错误:

OpenQA.Selenium.WebDriverException : Unexpected error. Unable to find element using     css: tr[svd='${surveyName}'] 

如果我像这样“硬编码”选择器:

Driver.FindElement(By.CssSelector("tr[svd='Selenium test survey']")) 

它找到了元素。

svd 是 tr 元素的一个属性。我试图通过此属性的值在表中选择一行。每个测试的文本都不同,因此必须是一个变量。

我尝试过用多种不同的方式来表达变量,但没有成功。任何帮助将不胜感激。

谢谢。

请您参考如下方法:

string surveyName = "Selenium test survey"; 
Driver.FindElement(By.CssSelector(String.Format("tr[svd='{0}']", surveyName)) 

会做你想做的。这是 C#,所以当它需要一个字符串时,您可以做各种事情来获取该字符串