c# - 如何从父元素获取文本并从子元素中排除文本(C# Selenium)

标签 c# selenium selenium-webdriver

在 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 problemselenium 中,因为您不能直接访问文本节点 - 换句话说,您的 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/

相关文章:

c# - Ajax 请求 WCF 数据(JSON 格式)但出现错误并显示成功消息

java - 无法使用 phantomjs 驱动程序运行 selenium 脚本

Python-使用selenium获取新网页的链接

java - 使用 Selenium 3.0 启动 Firefox 46.0.1 时出现 IllegalStateException

javascript - 如何使用 XPath 或 CSS 选择可见元素?

Javascript 链接在 selenium excel vba 中没有响应

javascript - 对于企业应用程序,输入验证应该是客户端还是服务器端?

C# 进程 <实例>.StandardOutput InvalidOperationException "Cannot mix synchronous and asynchronous operation on process stream."

c# - 当前上下文错误

c# - 限制 NUnit 项目中的并行线程数