【问题标题】:Selenium: How to find text on page containing html tags? (Text Node)Selenium:如何在包含 html 标签的页面上查找文本? (文本节点)
【发布时间】:2021-07-21 09:38:28
【问题描述】:

我在回答后更新了问题!

我尝试在网页的列表中查找文本,其中包含类似<p> text </p> 的html 标签。

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

在“inspect”中,我使用了//*[text()='<p> First do this, then this</p>'],如上图所示。

在代码中我使用这个代码行来查找文本:

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

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

OpenQA.Selenium.NoSuchElementException:没有这样的元素:无法定位元素:{"method":"xpath","selector":"//*[text()=' 先做这个,再做这个']"}

如您所见,selenium 确实忽略了 html 标签&lt;p&gt; &lt;/p&gt;

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

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

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

这里的输出是: &lt;p&gt; First do this, then this&lt;/p&gt;

【问题讨论】:

  • 你能不能也标记你的绑定语言,看起来它是 C# 。另外,我们可以有更多的outerHTML

标签: selenium selenium-webdriver selenium-chromedriver


【解决方案1】:

这是一个文本节点,你不能简单地使用 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);

【讨论】:

  • 不,//* 表示选择当前节点,所以如果文本是唯一的,它应该可以工作。也是 C# 吗?
  • 第一:OpenQA.Selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[text()='First do this, then this']"} 第二:OpenQA.Selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//p[text()='First do this, then this']"} 第三:OpenQA.Selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//p[contains(text(),'First do this, then this')]"}
  • 你能告诉我你的绑定语言吗?
  • 标签&lt;p&gt; 是文本的一部分。查看屏幕截图。您会在左侧的列表中看到这些标签显示在那里。同样在右侧的检查中,您会看到它们显示在那里。
  • 有效!!!非常感谢!您可以编辑您的答案,以便我将其标记为已回答吗?
【解决方案2】:

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

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

【讨论】:

  • 收到此错误消息:OpenQA.Selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//p[contains(text(),'First do this, then this')]"}
  • 尝试在此行之前添加等待/延迟以让页面完全加载。也可能是 iframe 中的元素。
  • 在我们的例子中,p 是文本的一部分。我们的应用程序有一个创建按钮。按下它后,有一个 ql 编辑器,我在其中输入一些文本。按下保存按钮后,此文本将被格式化并获得“html”标签。这些都是必需的,因为我们的客户在手机上通过 SMS 接收消息。这些 html 标签有助于在客户的手机上正确显示消息。在上面的截图中,你可以看到,标签是文本的一部分
  • 我已经等待了 5 秒钟,然后它才开始查找文本。这也是我的第一个猜测,它速度太快了,但即使等待,它也找不到文本
  • 即使&lt;p&gt; 是文本的一部分,由于我正在搜索文本“包含”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
  • 2012-01-13
  • 2010-10-26
  • 1970-01-01
  • 2017-01-24
  • 2013-10-09
相关资源
最近更新 更多