我正在谈论的元素如下:
<tbody>
<tr id="tableUsers_0__TR" class="active" name="Tr_tableUsers[0]_Selected">
<td>
<input id="tableUsers_0__POSName" type="hidden" value="Indian" name="tableUsers[0].POSName"/>
Indian
</td>
我建议的解决方案是:第一步是通过Xpath定位元素:
string xpath = ".//*[@id='tableUsers_0__PDVCode']/..";
然后使用方法获取Text:
driver.FindElement(By.XPath(xpath)).Text
这是最好的方式?或不?还有另一种比这种方式更好的方法吗?比使用Xpath更好。
1)你可以使用选择器By.Id("your id")
。
2)对于某些元素,使用IWebElement.GetAttribute("text")
比使用IWebElement.Text
更有用
Javascript Executor也可用于返回元素的文本。可以使用以下脚本:
document.getElementById('<your id>').innerText
要么
document.getElementById('<your id>').textContent
为此,必须首先创建JavascriptExecutor的对象。请参阅以下脚本:
IWebDriver driver; // driver object is created in the code somewhere
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string valueFromId = (string)js.ExecuteScript("return document.getElementById('<your id>').innerText");
您还可以通过在浏览器控制台中运行javascript命令(qazxsw poi ...)来验证此文本。
是的,这是一个比document.ge
使用Xpath
最好的方法: -
By.id
或者使用driver.FindElement(By.Id("tableUsers_0__TR")).Text
: -
By.CssSelector
注意: - 总是给driver.FindElement(By.CssSelector("tr#tableUsers_0__TR td")).Text
定位器的最后一个优先级,因为它比其他定位器慢得多,在你的情况下如果元素具有Xpath
属性而不是使用id
的最佳方式其他明智的尝试使用其他定位器如By.Id()
,By.Name()
,By.ClassName()
定位元素等等如果可能的话。