繁体   English   中英

如何从跨度嵌套获取文本-硒-C#

[英]How to get text from span nested - selenium - c#

我有这个HTML:

<span class="title-book">
   Sherlock_Holmes
   <span class="count-market">834</span>
</span>

我只想提取第一个跨度的值,我尝试了两种方法:

IList<IWebElement> ListBooks = MenuAll.FindElements(By.XPath("//span[@class='title-book']"));

IList<IWebElement> ListBooks = MenuAll.FindElements(By.CssSelector(".title-book"));

但是我得到以下结果: Sherlock_Holmes834

为什么?

问题在于span.title-book元素不仅保存所需的文本,而且还保存另一个包含文本“ 834”的SPAN “ Sherlock_Holmes”文本被认为是文本节点,不能仅使用Selenium来检索,我们必须使用Javascript来获取它。

/// <summary>
/// Returns the text of the specified child text node.
/// </summary>
/// <param name="parentElement">The parent <see cref="IWebElement"/> of the desired text node.</param>
/// <param name="index">The index of the childNode collection relative to parentElement</param>
/// <returns>The text of the specified child text node.</returns>
public string GetChildTextNode(IWebElement parentElement, int index = 0)
{
    string s = (string)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].childNodes[arguments[1]].textContent;", parentElement, index);
    return s.Trim();
}

你会这样称呼

Console.WriteLine(GetChildTextNode(driver.FindElement(By.CssSelector("span.title-book"))));

文本Sherlock_Holmes<span class="title-book"> ... </span>标记内。 因此,要检索文本Sherlock_Holmes ,可以使用以下代码块:

IWebElement elem = driver.FindElement(By.XPath("//span[@class='title-book']"));
string myText = (string)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].firstChild.textContent;", elem);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM