Shivani Maheshwari
Shivani Maheshwari

Reputation: 1

Create a WebElement array from a string array

I want to create a WebElement list from a String array by using Findby in Selenium.

My String array has this value:

String [] s1 = {"Sale Condo", "Rent Condo"};

And I am looping this String array to create a list of WebElement by doing this:

List<WebElement> allElem=new ArrayList<WebElement>();
for (String s: s1){
    @FindBy(linkText=s)
    allElem.add();
}

I am not able to do it. Please help on how can I accomplish this.

Upvotes: 0

Views: 2334

Answers (2)

Cosmin
Cosmin

Reputation: 2394

I'm not 100% sure if this is applicable for java too, but for C# you cannot do it this way, because the FindsBy[] attribute is expecting a constant value for the Using. Meaning the following code works fine:

[FindsBy(How = How.Id, Using = "elementID")]
private IWebElement Element {get; set;}

But this one errors out:

string idOfTheElement = "elementID";
[FindsBy(How = How.Id, Using = idOfTheElement)]
private IWebElement Element {get; set;}

However you could achieve this by using getters:

string[] array = new string[] {"id1", "id2"};
List<IWebElement> allElem = new List<IWebElement>();
foreach(var s in array)
{
    var element = driver.FindElement(By.Id(s));
    allElem.Add(element);
} 

Upvotes: 0

Madhan
Madhan

Reputation: 5818

Are you sure that's not throwing an compiler error.

You can use something like this

List<WebElement> allElem=new ArrayList<WebElement>();
for (String s: s1){
    allElem.add(driver.findElement(By.linkText(s)));
}

Upvotes: 2

Related Questions