【问题标题】:How to get text from span nested - selenium - c#如何从嵌套的范围内获取文本 - selenium - c#
【发布时间】:2018-05-11 02:00:07
【问题描述】:

我有这个 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[@class='title-book']//*[not(span[@class='count-market'])]

标签: c# selenium selenium-webdriver xpath webdriver


【解决方案1】:

问题在于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"))));

【讨论】:

    【解决方案2】:

    文本 Sherlock_Holmes 位于 &lt;span class="title-book"&gt; ... &lt;/span&gt; 标记内。因此,要检索文本 Sherlock_Holmes,您可以使用以下代码块:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      相关资源
      最近更新 更多