【问题标题】:css/xpath selector to exclude the child node in the element when using selenium webdriver (java)css/xpath 选择器在使用 selenium webdriver (java) 时排除元素中的子节点
【发布时间】:2017-10-10 16:00:21
【问题描述】:

CSS/xpath 选择器获取链接文本,不包括.muted 中的文本。

我有这样的html:

<a href="link">
          Text
   <span class="muted"> –text</span>
</a>

当我执行getText() 时,我会得到完整的文本,例如Text-text。是否可以排除静音的子类文本?

试过cssSelector = "a:not([span='muted'])" 不起作用。

xpath = "//a/node()[not(name()='span')][1]"

错误:xpath 表达式"//a/node()[not(name()='span')][1]" 的结果是:[objectText]。它应该是一个元素。

【问题讨论】:

  • cssSelector = "a span:not(.muted) 应该可以工作
  • 谢谢@winner_joiner。但这不起作用。它返回一个空集。

标签: xpath selenium-webdriver css-selectors


【解决方案1】:

您无法使用 Selenium WebDriver 的 API 执行此操作。您必须在代码中按如下方式处理它:

// Get the entire link text
String linkText = driver.findElement(By.xpath("//a[@href='link']")).getText();

// Get the span text only
String spanText = driver.findElement(By.xpath("//a[@href='link']/span[@class='muted']")).getText();

// Replace the span text from link text and trim any whitespace
linkText.replace(spanText, "").trim();

【讨论】:

  • 谢谢。这有帮助。
【解决方案2】:

AFAIK 仅使用 CSS 选择器无法做到这一点。您可以尝试使用JavaScriptExecutor 来获取所需的文本。

由于您没有提及您使用的编程语言,我在Python 上向您展示了示例:

link = driver.find_element_by_css_selector('a[href="link"]')
driver.execute_script('return arguments[0].childNodes[0].nodeValue', link)

这将只返回 "Text" 而没有 " -text"

【讨论】:

  • 谢谢。这可行,但正在寻找是否还有其他方法。可能使用 xpath 选择器或 jquery ?
  • XPath 获取所需文本是normalize-space(//a[@href="link"]/text()),但selenium 不支持这种语法...
猜你喜欢
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2014-08-08
相关资源
最近更新 更多