重复使用Selenium方法2种不同的情况

时间:2014-09-23 12:08:26

标签: java selenium selenium-webdriver

我有一个定义如下的Selenium方法。该方法接受personName字符串并尝试查找" li"删除任何空格后的元素。

现在我想重复使用相同的方法来检查

  
      
  1. 没有空格(personNameWithoutSpaces)
  2.   
  3. with spaces(personName)
  4.   

如何更新以下方法以适用于两种情况(因为在一个页面上,名称可以不带空格呈现,而在其他页面中,它是用空格呈现的)?

public WebElement getPersonByText( String personName ) {
    String personNameWithoutSpaces = personName.replaceAll("\\s+","");
    return getHelper().getVisibleElement( By.xpath("//div[@id='display']//li[contains(@class, 'person') and contains(.,'" + personNameWithoutSpaces + "')]") ); 
}

public WebElement getVisibleElement( final By by ) {
        return getVisibleElement( by, DEFAULT_TIMEOUT, TimeUnit.SECONDS, DEFAULT_TIME_INTERVAL, TimeUnit.MILLISECONDS);
    }

不确定我是否需要使用2个try ... catch块或者如果我需要使用if..else语句,,,

1 个答案:

答案 0 :(得分:0)

根据OP的评论,

 public WebElement getPersonByText( String personName ) {

    try{
       driver.findElement(By.xpath("//div[@id='display']//li[contains(@class, 'person') and contains(.,'" + personName + "')]") 
       return getHelper().getVisibleElement( By.xpath("//div[@id='display']//li[contains(@class, 'person') and contains(.,'" + personName + "')]") );

        }
     catch(NoSuchElementException e){
         String personNameWithoutSpaces = personName.replaceAll("\\s+","");
         return getHelper().getVisibleElement( By.xpath("//div[@id='display']//li[contains(@class, 'person') and contains(.,'" + personNameWithoutSpaces + "')]") );
      }

}
相关问题