Mac*_*tyn 11 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>
Run Code Online (Sandbox Code Playgroud)
在C#(或任何语言)中,我将:
string linktext = driver.FindElement(By.CssSelector(".linksSection > a#google")).Text;
Assert.AreEqual(linkText, "Google Link", "Google Link fails text test.");
Run Code Online (Sandbox Code Playgroud)
但是,linktext将具有"谷歌链接此链接将带您到谷歌的主页."
没有做一堆字符串操作(比如获取所有子节点的文本并从父节点的结果文本中减去它),有没有办法从父元素中获取文本?
ale*_*cxe 13
这是一个常见问题,selenium因为您无法直接访问文本节点 - 换句话说,您的XPath表达式和CSS选择器必须指向实际元素.
以下是您的问题的可能解决方案列表:
Google Link在你的情况下.Google Link公正的断言,你可能会检查父母的文本是否适合 Google Link.见StringAssert.StartsWith().获取outerHTML父文本的文本并将其提供给HTML Parser,例如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());
Run Code Online (Sandbox Code Playgroud)