在 Selenium 中是否可以仅从父元素而不是其子元素获取文本?
例子:
假设我有以下代码:
<div class="linksSection>
<a href="https://www.google.com/" id="google">Google Link
<span class="helpText">This link will take you to Google's home page.</span>
</a>
...
</div>
在 C#(或任何语言)中,我将有:
string linktext = driver.FindElement(By.CssSelector(".linksSection > a#google")).Text;
Assert.AreEqual(linkText, "Google Link", "Google Link fails text test.");
但是,链接文本将包含“Google Link此链接将带您进入 Google 主页”。
如果不进行大量字符串操作(例如获取所有子元素的文本并从父元素的结果文本中减去该文本),有没有办法只从父元素获取文本?
这是一个常见问题 https://code.google.com/p/selenium/issues/detail?id=5459 in selenium
因为您无法直接访问文本节点 - 换句话说,您的 XPath 表达式和 CSS 选择器必须指向实际元素。
以下是您的问题的可能解决方案列表:
- 获取父元素的文本,对于每个子元素,获取文本并将其从父元素的文本中删除。您留下的是所需的文本 -
Google Link
在你的情况下。
- 如果你想得到
Google Link
只是为了做出断言,您可能可以检查父母的文本是否正确馅饼与 Google Link
. See StringAssert.StartsWith() https://msdn.microsoft.com/en-us/library/ms243970.aspx.
-
get the outerHTML
父级文本并提供给 HTML 解析器,例如Html Agility Pack http://html-agility-pack.net/?z=codeplex。沿着这些思路:
string outerHTML = driver.FindElement(By.CssSelector(".linksSection > a#google")).GetAttribute("outerHTML");
HtmlDocument html = new HtmlDocument();
html.LoadHtml(outerHTML);
HtmlAgilityPack.HtmlNode a = html.DocumentNode.SelectNodes("//a[@id='google']");
HtmlNode text = strong.SelectSingleNode("following-sibling::text()");
Console.WriteLine(text.InnerText.Trim());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)