在 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 LinkThis link will take you to Google's home page.”
如果不进行一堆字符串操作(例如获取所有子元素的文本并从父元素的结果文本中减去该文本),是否有办法只从父元素获取文本?
最佳答案
这是一个 common problem在 selenium
中,因为您不能直接访问文本节点 - 换句话说,您的 XPath 表达式和 CSS 选择器必须指向实际元素。
以下是针对您的问题的可能解决方案列表:
- 获取父元素的文本,对于每个子元素,获取文本并将其从父元素的文本中移除。您剩下的就是所需的文本 -
Google Link
在您的案例中。 - 如果您想要获取
Google 链接
只是为了做出断言,您可以检查 parent 的文本是否以 开头谷歌链接
。参见StringAssert.StartsWith()
. 获取父文本的
outerHTML
并提供给 HTML 解析器,例如Html Agility Pack
.沿着这些线的东西: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());
关于c# - 如何从父元素获取文本并从子元素中排除文本(C# Selenium),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28945692/