如何将字符串转换为By类型 [英] How to convert string to By type

查看:462
本文介绍了如何将字符串转换为By类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将String转换为By类型。

How to convert String to By type.

以下是我的场景:
以下面的方式在属性文件中保留对象

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

username=By.id("username")
password=By.id("password")

在应用程序中,我想检索像

In the application i would like to retrieve the values like

Properties prop=new Properties();
prop.load("above properties file path")

driver.findelement(prop.getProperty(username)) //在eclipse中,它抱怨说WebDriver类型中的方法findElement(By)不适用于参数(String)

driver.findelement(prop.getProperty("username")) //Here in eclipse it is complaining saying "The method findElement(By) in the type WebDriver is not applicable for the arguments (String)"

那么有人可以帮助我吗?

So can somebody help me in this?

我可以使用如下或其他格式,但我想要上述解决方案

I can use like below or some other format, but i want solution for the above

username="//*[@id='username']"
username="username"
driver.findElement(By.xpath(prop.getProperty("username"))
driver.findElement(By.id(prop.getProperty("username"))


推荐答案

您可以创建一个解析器方法,它将返回所需的定位器对象,如下所示:

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")));

为id,name,xpath添加了逻辑。您可以修改相同的方法来添加所有可用的定位器。希望这有帮助!

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

这篇关于如何将字符串转换为By类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆