我需要来自Iwebelement的Xpath的值。有人可以帮我吗? PFB代码
IWebElement webElement;
if (!string.IsNullOrEmpty(webElement.GetAttribute("id")))
{
searchprop.Add("Id", webElement.GetAttribute("id"));
}
if (!string.IsNullOrEmpty(webElement.GetAttribute("XPath")))
{
searchprop.Add("XPath", webElement.GetAttribute("XPath"));
}
在这里,很明显我无法使用" webElement.GetAttribute(" XPath")"来获取Xpath值。由于Xpath不是一个属性。与ID值类似,我也需要Xpath。那我怎么能得到它呢?
答案 0 :(得分:0)
也许这种方法可以解决您的问题。
public String GetElementXPath(IWebDriver driver, IWebElement element)
{
String javaScript = "function getElementXPath(elt){" +
"var path = \"\";" +
"for (; elt && elt.nodeType == 1; elt = elt.parentNode){" +
"idx = getElementIdx(elt);" +
"xname = elt.tagName;" +
"if (idx > 1){" +
"xname += \"[\" + idx + \"]\";" +
"}" +
"path = \"/\" + xname + path;" +
"}" +
"return path;" +
"}" +
"function getElementIdx(elt){" +
"var count = 1;" +
"for (var sib = elt.previousSibling; sib ; sib = sib.previousSibling){" +
"if(sib.nodeType == 1 && sib.tagName == elt.tagName){" +
"count++;" +
"}" +
"}" +
"return count;" +
"}" +
"return getElementXPath(arguments[0]).toLowerCase();";
return (String)((IJavaScriptExecutor)driver).ExecuteScript(javaScript, element);
}