Selenium:如何在包含 html 标签的页面上查找文本? (文本节点)

Selenium: How to find text on page containing html tags? (Text Node)

问题回答后更新了!

我试图在网页的列表中找到一段文字,其中包含一个 html 标签,例如 <p> text </p>

这是网页上的截图: Screenshot of text to search for

在“检查”中,我使用了 //*[text()='<p> First do this, then this</p>'],可以在上面的屏幕截图中找到。

在我使用此代码行查找文本的代码中:

webDriver.FindElement(By.XPath("//*[text()='<p> First do this, then this</p>']"))

但是在测试期间运行它给出了这个错误信息:

OpenQA.Selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[text()=' First do this, then this']"}

如您所见,selenium 确实以某种方式忽略了 html 标签 <p> </p>

来自cruispandey的回答和解决方案:

感谢@cruisepandey 我现在知道了,我的文本在文本节点中。 获取文本的唯一方法是使用此代码:

var ele = webDriver.FindElement(By.XPath("//table[@class='mud-table-root']//tbody/tr[1]/td[2]"));
        Console.WriteLine(ele.Text);

这里的输出是: <p> First do this, then this</p>

p 是元素标签名称,不是其文本的一部分。
文本中也可能有空格。在这种情况下,我更喜欢使用 contains 而不是完全等式文本检查。
试试这个:

webDriver.FindElement(By.XPath("//p[contains(text(),'First do this, then this')]"))

那是一个文本节点,您不能简单地使用 xpath v1.0

中的 text() 方法

您可以尝试使用以下 xpath :

(//table[@class='mud-table-root']//tbody/tr)[1]/td[2]

代码:

var ele = webDriver.FindElement(By.XPath("//table[@class='mud-table-root']//tbody/tr[1]/td[2]/text()"));
Console.WriteLine(ele.Text);

代码(有显式等待): 在你想要点击它的地方。

var ele = new WebDriverWait(webDriver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("(//table[@class='mud-table-root']//tbody/tr)[1]/td[2]")));
Console.WriteLine(ele.Text);