温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - How to pass string to an XPath containing text?
c# selenium selenium-webdriver winforms xpath

c# - 如何将字符串传递到包含文本的XPath?

发布于 2020-04-11 23:20:51

我使用以下代码获取使用Selenium Webdriver在选定模式下的文本的ID:

String requiredId = driver.FindElement(By.XPath("//option[@selected='selected' and .='Blue']/..")).GetAttribute("id");

如何传递字符串getColour代替Blue?

谢谢

查看更多

提问者
by dukaan
被浏览
115
Muzzamil 2020-02-02 13:17

您可以通过这种方式传递字符串。试试下面的代码

    string getColourin = "Red";
    String requiredId = driver.FindElement(By.XPath("//option[@selected='selected' and .='" + getColourin +"']/..")).GetAttribute("id");

要么

使用string.Format

string xpathBefore = "//option[@selected='selected' and .='{0}']/..";
string getColourin = "Red";
string finalXpath = string.Format(xpathBefore, getColourin);

String requiredId = driver.FindElement(By.XPath(finalXpath)).GetAttribute("id");