在XPath中使用变量

时间:2019-02-07 12:59:50

标签: c# selenium selenium-webdriver xpath xpath-1.0

这是可行的,但是我想使用文本 Group 1 作为变量。

代码试用:

[FindsBy(How = How.XPath, Using = "(.//*[normalize-space(text()) and normalize-space(.)= 'Group 1'])[1]/ancestor::app-organization//*[normalize-space(text()) and normalize-space(.)='Create a new board...']/following::input[1]")]
public IWebElement BoardNameInputField { get; set; }

我尝试过但没有成功:

string boardName = "Group 1";

[FindsBy(How = How.XPath, Using = "(.//*[normalize-space(text()) and normalize-space(.)='${boardName}'])[1]/ancestor::app-organization//*[normalize-space(text()) and normalize-space(.)='Create a new board...']")]
public IWebElement CreateNewBoard { get; set; }

可以这样做吗?

3 个答案:

答案 0 :(得分:5)

在字符串插值中,$("table-class-name .input-class-name).each(function(){ $(this).attr("disabled","true"); }); 应该在字符串之前,而不是变量之前

$

此外,[FindsBy(How = How.XPath, Using = $"(.//*[normalize-space(text()) and normalize-space(.)='{boardName}'])[1]/ancestor::app-organization//*[normalize-space(text()) and normalize-space(.)='Create a new board...']")] 必须是静态的,才能在方法范围之外使用

boardName

答案 1 :(得分:2)

您可以将String.Formatinserting-a-string结合使用:

string boardName = "Group 1";

[FindsBy(How = How.XPath, Using = String.Format("(.//*[normalize-space(text()) and normalize-space(.)='{0}'])[1]/ancestor::app-organization//*[normalize-space(text()) and normalize-space(.)='Create a new board...'])", boardName)]
public IWebElement CreateNewBoard { get; set; }

希望这对您有帮助!

答案 2 :(得分:-1)

在将变量 boardName 设置为 Group 1 时,您需要更改:

How.XPath, Using = "(.//*[normalize-space(text()) and normalize-space(.)='${boardName}'])[1]/ancestor::app-organization//*[normalize-space(text()) and normalize-space(.)='Create a new board...']")]

为:

How.XPath, Using = "(.//*[normalize-space(text()) and normalize-space(.)='" + boardName + "'])[1]/ancestor::app-organization//*[normalize-space(text()) and normalize-space(.)='Create a new board...']")]

实际上我们进行了更改:

normalize-space(.)='${boardName}'

收件人:

normalize-space(.)='" + boardName + "'