How to convert string to By type

后端 未结 4 1743
春和景丽
春和景丽 2021-01-27 06:43

How to convert String to By type.

Following is my scenario: Keep object identification in Properties file in below manner

username=By.id(\"username\")
pa         


        
4条回答
  •  花落未央
    2021-01-27 07:34

    You can create one parser method which will return desired locator object something like below:

    public static By locatorParser(String locator) {
    
    By loc = By.id(locator);
    
    if (locator.contains("id"))
        loc = By.id(locator.substring(locator.indexOf("\"") + 1,
            locator.length() - 2));
    
    else if (locator.contains("name"))
        loc = By.name(locator.substring(locator.indexOf("\"") + 1,
            locator.length() - 2));
    
    if (locator.contains("xpath"))
        loc = By.xpath(locator.substring(locator.indexOf("\"") + 1,
            locator.length() - 2));
    
    return loc;
    
    }
    

    Can be called in your code in the following way:

    driver.findElement(locatorParser(prop.getProperty("username")));
    

    Added logic for id, name, xpath. You can modify the same method to add all the available locators. Hope this helps!

提交回复
热议问题