【问题标题】:How to retrieve the text from a text node within an element through Xpath, C# and Selenium如何通过 Xpath、C# 和 Selenium 从元素内的文本节点检索文本
【发布时间】:2018-05-23 09:42:30
【问题描述】:

我是一名测试自动化工程师,过去几年一直在 selenium 工作这是我在 Stackoverflow 上的第一篇文章。

我正在尝试从元素中获取文本,但 selenium 甚至无法识别元素。我使用 Visual Studio 中的 specflow 设置和 c# 作为语言。

以下是示例 html 代码(这只是 HTML 代码的示例结构,不是原始代码):

<p class="day">
 <meta atts="somevalue">
 <span>Some text</span>
 <meta atts="somevalue">
 <meta atts="somevalue">
 "Active"
</p>

我想从上面的 HTML 中获取文本 Active

我为此编写了多个 xpath,当我在 chrome 中检查时,xpath 是正确的并且它正在突出显示元素

Xpaths 试验:

1. //p[@class='day']/text()
2. //p[@class=''day]/meta[@atts='somevalue'][3]/following-sibling::text()
3. few more..

对于所有 xpath text() 介于两者之间或末尾。当我手动检查时,所有这些都是正确且唯一的。

我正在自动化的网页中不涉及任何框架。也没有页面加载问题。我尝试过使用不同的等待语句。还尝试了一个长 thread.sleep()。

元素的位置总是相同的。只有其中的值会改变。即,该元素的 xpath 不是动态的。

我在下面的行中收到错误。 (驱动程序已正确初始化,它适用于其他一切)

String StatusVal = driver.FindElement(By.XPath("(//meta[@itemprop='closes'])[1]/following-sibling::text()")).Text;

无论我尝试什么,我都会收到以下错误消息,提示找不到元素,

OpenQA.Selenium.NoSuchElementException: Could not find element by: By.XPath: (//meta[@itemprop='closes'])[1]/following-sibling::text()

以上是实际的xpath,如果我在同一个浏览器中测试失败后手动检查xpath,它在那里可用并且是唯一的。

即,在我的分析中,我的 xpath 是正确的,不涉及任何框架,页面中没有等待问题,因为我正在成功地对附近的元素执行操作,并且我为页面提供了足够的时间加载。所有正常的 selenium 设置都在我的系统中完成,除此之外一切正常。

硒版本:3.12.0

【问题讨论】:

  • 在您的 HTML 中,您有 @atts,但您的错误消息包含 @itemprop
  • 这只是 html 代码的示例结构。我不能在这里使用原来的

标签: c# selenium-webdriver xpath webdriver selenium-chromedriver


【解决方案1】:

根据您提供的HTML 来检索文本Active,您可以使用IJavaScriptExecutor Interface 中的ExecuteScript() 方法,如下所示:

IWebElement myElem = driver.FindElement(By.XPath("//p[@class='day']"));
string myText = (string)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].lastChild.textContent;", myElem);
Console.WriteLine(myText);

【讨论】:

    猜你喜欢
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 2020-10-08
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多