AMJ
AMJ

Reputation: 23

Iterate through web elements with Selenium and Robot Framework

On the web page there are many elements with the same span class name. And I'm able to get the value of the first element with keyword "Get Text class: ...".

But I just can not figure it out how to iterate and get the values of all those same span class names. Any ideas?

I know how to iterate e.g. a text file with Python, but I'm not yet familiar enough with Selenium and RFW.

Upvotes: 2

Views: 21706

Answers (3)

Yash Jagdale
Yash Jagdale

Reputation: 1508

Here is the solution which you can try to itrate over all the element. But if you want to take 1st element only then you can create xpath and then add (your xpath)[1] to fetch 1st element. Similarly there is :nth-childOf(). Read more here

xpath=<<your identifier>>
${all_ele_count}=    Get Matching Xpath Count    xpath=<<your identifier>>
Log    ${all_ele_count}
: FOR    ${INDEX}    IN RANGE    1    ${all_ele_count}
\    Log    ${INDEX}
\    ${currUrl}    get location
\    click element    xpath=(<<your identifier>>)>1])[1]
\    do processing here
\    go to    ${currUrl}

Upvotes: -1

Neha
Neha

Reputation: 316

You can also get all the elements with the span class in an arraylist and iterate over them. eg:

ArrayList<WebElement> list = new ArrayList<WebElement>();
list.add(driver.findElements(By.class("")));
for(int i=0; i<list.size(); i++)
{
//select the element which is needed
}

I hope this works

Upvotes: -2

Bence Kaulics
Bence Kaulics

Reputation: 7271

You can get all web elements with same class using the Get WebElements keyword, and then you can iterate them with a for loop. Note that I am using the RF 3.1 new for syntax. You can access the text attribute using the extended variable syntax.

${elements}=    Get WebElements    //span[@class='myclass']
FOR    ${element}    IN    @{elements}
    Log    ${element.text}
END

Other option is to use the Get Text keyword inside the loop, you can pass the web element variable as a locator.

${elements}=    Get WebElements    //span[@class='myclass']
FOR    ${element}    IN    @{elements}
    ${text}=    Get Text    ${element}
    Log    ${text}
END

Upvotes: 13

Related Questions