【问题标题】:How to use @FindBy annotation in Selenium for span text?如何在 Selenium 中使用 @FindBy 注释来处理跨度文本?
【发布时间】:2018-05-31 08:16:09
【问题描述】:

我想知道如何使用@FindBy 注释在 span 元素中获取“Ap​​ple”文本。

这是html代码:

<span class="ui-cell-data">Apple</span>

我尝试了类似的方法:

@FindBy(className = "ui-cell-data:Samsung")
WebElement customerName;

但它没有用!

【问题讨论】:

  • findby的classname值后面加':Samsung'有什么必要?
  • 此外,ui-cell-data 感觉像相当广泛的类,并且还可能匹配其他不受欢迎的元素。不过,您还没有显示页面的标记,目前无法判断。

标签: java maven selenium findby


【解决方案1】:

根据您分享的HTML,您可能/可能无法在 span 元素中获取 Apple 文本:

@FindBy(className = "ui-cell-data")
WebElement customerName;

您的代码几乎完美,但 className 中的尾随部分为 :Samsung 是不必要的。

但是,再次查看class 属性,预计会有更多的&lt;span&gt; 标签具有相同的class。因此,要唯一标识预期的 WebElement,我们需要引用父节点并跟随其后代到达此特定节点。

最后,使用给定的HTML,下面的代码块会更简洁:

  • cssSelector

    @FindBy(cssSelector = "span.ui-cell-data")
    WebElement customerName;
    
  • xpath

    @FindBy(xpath = "//span[@class='ui-cell-data']")
    WebElement customerName;
    

【讨论】:

    【解决方案2】:

    你可以试试下面的 xpath

     @FindBy(xpath = "//span[@class = 'ui-cell-data']") 
     private WebElement element;
    

    【讨论】:

      【解决方案3】:

      你可以像链式元素查找一样使用@FindBys

      @FindBys({@FindBy(className = "ui-cell-data")})
      private WebElement element;
      

      或尝试使用以下:

      @FindBy(xpath = "//*[@class = 'ui-cell-data']")
      private WebElement element;
      

      @FindBy(css = ".ui-cell-data")
      private WebElement element; 
      

      希望它能解决您的问题。

      【讨论】:

      • @meert 嘿兄弟!它对你有用吗?请让我知道您的反馈。
      猜你喜欢
      • 2013-05-06
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      相关资源
      最近更新 更多