How to convert string to By type

后端 未结 4 1745
春和景丽
春和景丽 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:30

    The WebDriver.findElement method accepts only an object parameter of the type By. The Property.getProperty method returns only a String typed object.

    Therefore, this may be what fits your need:

    WebElement element = driver.findElement(By.name(prop.getProperty("username")));
    

    You can't force a String typed object into a method that accepts only a By typed object. When you ask Selenium to find a String "username" you have to tell it more than just the string's value.

    The method By.[method] you choose all depends on what you are looking for in the page that Selenium is searching. "username" is most likely the "name" (By.name) or "id" (By.Id) of the field you are looking for. The By class refines the search to where you expect the String "username" to be: in a name, id, tag, class, etc. See the By class definition.

    Also, take caution as the getProperty method could return a null, and the By methods with throw an IllegalArgumentException if you pass it a null string. So providing a default return value ("") for getProperty is usually safer.

    WebElement element = driver.findElement(By.name(prop.getProperty("username", "")));
    

提交回复
热议问题