繁体   English   中英

如何在Selenium Web驱动程序的单个变量中存储所有不同类型的定位符(xpath,Css,Link,ID等)

[英]How to store all different types of locators(xpath, Css, Link, ID etc) in a single variable in selenium web driver

我想将所有不同类型的定位符*(xpath,Css,链接,ID等)*存储在单个变量中,并对它执行一些操作,如以下语句所示。

webdriver.findelement(variable).click(); ”此处的变量可能是“ b y.id,by.xpath,by.css..etc ”“我编写了以下代码,但被困于将字符串转换为Web元素以对其执行一些操作。

public void Element(){          
        try{
              String locator = new String("xpath=//div[@id='pageTitle']");
                  if(locator.startsWith("//"))
                  System.out.println("Locator value if 
                          starts with slash is\t" +locator);
              else 
              {
                  if(locator.contains("=")){
                  String retnval[] = locator.split("=");
                  String type = "findElement(By."+retnval[0]+"(";            
                  int index= locator.indexOf("=");
                  locator=locator.substring((index)+1);                   
                  String element =type.concat(locator+")");
                  System.out.println(element);
                   getElement.click();
                 }
            }
        }
        catch (Exception e){
          System.out.println(e);
        }
    }

输出为:

findElement(By.xpath(//div[@id='pageTitle'])

我知道下面的代码,但是想尝试一些不同的方法而无需在代码中使用定位器类型(xpath,id,css,name等) ,或者帮助我知道如何将字符串转换为Web元素。

if(locator.contains("xpath="))
                    locator = locator.substring(6);
                webDrvElement = webDriver.findElement(By.xpath(locator));
            }
            else if(locator.contains("id=")){
                locator = locator.substring(3);
                webDrvElement = webDriver.findElement(By.id(locator));
            } 
            else if(locator.contains("name=")){
                locator = locator.substring(5);
                webDrvElement = webDriver.findElement(By.name(locator));
            } 
            else if(locator.contains("css=")){
                locator = locator.substring(4);
                webDrvElement = webDriver.findElement(By.cssSelector(locator));
            }

这可以通过使用以下反射来实现:

 String locator = "xpath=//li[@id='menu-item-72']/a";
 String[] locatorValArr = locator.split("=");

 String locatorType = locatorValArr[0];
 String locatorValue = "";
 for(int i = 1; i < locatorValArr.length; i++)
     locatorValue += locatorValArr[i]+"=";
 locatorValue = locatorValue.replaceAll("\\=$", "");

 Class byClass = Class.forName(By.class.getName());
 Method getMethodBy = byClass.getMethod(locatorType, String.class);
 By newById = (By) getMethodBy.invoke(null, locatorValue);

 driver.findElement(newById).click();

我们可以对cssSelector,名称,类,ID和其他定位符类型进行相同的操作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM