我正在使用 selenium 并尝试从节点访问文本,但我不确定如何获取和断言已批准关键字的文本。
这是节点 -
<div class="Notification-body">
<div class="">
<div class="type--primary u-textBreak">
<span class="u-inline">
<span class="type--title">User Name</span> approved "Page_For_Submission"
</span>
</div>
<span class="u-displayBlock type--note">4 hours ago</span>
</div>
</div>
最初我试过这个 XPath 但它没有给出任何结果 -
(//span[contains(@class,'title')]/following-sibling::text()[contains(text(),'approved')])[1]
表示这不是一个简单的文本节点。
后来我使用了下面的XPaths并且能够定位元素的位置
(//html/body/div[7]/div[3]/div[2]/div/div/div/div/ul/li[2]/a/div/div/div/div/span/text())[2]
//span[contains(@class,'title')]/following-sibling::text()
(//span[contains(@class,'title')]/following-sibling::text()[contains(.,'approved')])[1]
但是通过在 selenium 中使用这些 XPaths
System.out.println(driver.findElement(By.xpath(prop.getProperty("txt_approvedNotification"))).getText());
执行时出现如下错误
org.openqa.selenium.InvalidSelectorException: invalid selector: The result of the xpath expression "(XPath of Element)[2]" is: [object Text]. It should be an element.
(Session info: chrome=77.0.3865.90)
Build info: version: '3.11.0', revision: 'e59cfb3', time: '2018-03-11T20:26:55.152Z'
System info: host: '*****', ip: '*****', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_191'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 77.0.3865.90,
只是想知道它的 XPath 问题或 seleniumdriver 限制。
最佳答案
Selenium 无法将单个特定文本节点包装到 WebElement 中。因此,作为灵魂,您可以准备并执行 JavaScript 代码来找到您需要的文本节点,将其包装到标签中并使用一些唯一 ID 添加到 DOM。然后您将能够使用 Selenium (findElement(By.id())
) 获取该元素。
关于html - 如何通过 XPath 检索 [object Text]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58113518/