Java 在HTML中按文本选择WebElement

Java 在HTML中按文本选择WebElement,java,selenium,automation,Java,Selenium,Automation,我尝试选择此WebElement已有一段时间了。这是我测试的web应用程序首页上的注册按钮。我想知道,有没有一种方法可以用来抓取HTML中的文本来定义WebElement 注册 注册 如果您仅绑定到xpath或 css查找 选项1 如果您愿意在助手方法中添加另一个案例,我想By.linkText可以满足您的需要吗 /** * @param linkText The exact text to match against * @return a By which locate

我尝试选择此WebElement已有一段时间了。这是我测试的web应用程序首页上的注册按钮。我想知道,有没有一种方法可以用来抓取HTML中的文本来定义WebElement


注册
注册
如果您仅绑定到xpathcss查找

选项1

如果您愿意在助手方法中添加另一个案例,我想By.linkText可以满足您的需要吗

  /**
   * @param linkText The exact text to match against
   * @return a By which locates A elements by the exact text it displays
   */
  public static By linkText(final String linkText) {
    if (linkText == null)
      throw new IllegalArgumentException(
          "Cannot find elements when link text is null.");

    return new ByLinkText(linkText);
  }
或者可能通过.partialLinkText

如果您正在针对已国际化的系统进行测试,这可能会成为一个问题。根据环境的不同,用户/浏览器的区域设置会更改您要查找的文本

如果文本更改,这也可能是维护问题

选项2

如果你有HTML控件,你可以考虑添加ID到页面上的元素。这样,您就可以使用By.id查找。根据我的一些初步研究,元素id被视为更可靠和一致的路径之一

/**
   * @param id The value of the "id" attribute to search for
   * @return a By which locates elements by the value of the "id" attribute.
   */
  public static By id(final String id) {
    if (id == null)
      throw new IllegalArgumentException(
          "Cannot find elements with a null id attribute.");

    return new ById(id);
  }
选项3

我的最后一个建议是尝试通过查找来实现自己的功能。我不建议为查找提供一个实现,但是如果这种行为是您所需要的,那么您应该意识到您可能会创建一个子类来完成您想要的任务


祝您好运。

对于旧的inlie样式css,您生成的css选择器取决于为div编写的样式,如
“div[style*='paste\u style\u attribute']”“
。然而,由于相同样式的重复,这种方法不可靠

以下部门:

<div style="font-family: franklin-gothic-ext-comp-urw; font-weight: 700; font-style: normal; font-size: 15px; opacity: 1; color: rgb(63, 63, 63); transform: translate(7px, 0px) scale(1, 1) rotate(0deg);">SIGN&nbsp;UP</div>
Java代码:

driver.findElement(By.cssSelector("div[style*='font-family: franklin-gothic-ext-comp-urw; font-weight: 700; font-style: normal; font-size: 15px; opacity: 1; color: rgb(63, 63, 63); transform: translate(7px, 0px) scale(1, 1) rotate(0deg);']"))

如果您可以通过css、xpath和。。您可以通过
.getText()
.getAttribute(“innerHTML”)
获取文本。问题是我无法通过css或xpath获取文本。然后您应该提供更多html:)
"div[style*='font-family: franklin-gothic-ext-comp-urw; font-weight: 700; font-style: normal; font-size: 15px; opacity: 1; color: rgb(63, 63, 63); transform: translate(7px, 0px) scale(1, 1) rotate(0deg);']"
driver.findElement(By.cssSelector("div[style*='font-family: franklin-gothic-ext-comp-urw; font-weight: 700; font-style: normal; font-size: 15px; opacity: 1; color: rgb(63, 63, 63); transform: translate(7px, 0px) scale(1, 1) rotate(0deg);']"))