How to iterate through child elements of a webelement?

I have a list of users on a webpage like this

<div id="users">
    <li class="user_list">
        <div class="users-name">User One</div>
        <div class="other details">...</div>
    </li>
    <li class="user_list">
        <div class="users-name">User Two</div>
        <div class="other details">...</div>
    </li>
</div>

I want to iterate through the list and get the names of the users like this

@{users_list}=    Get WebElements    xpath=//li[contains(@class, 'user_list')]
FOR    ${user}    IN    @{users_list}
    ${name_el}=    Get WebElement    xpath=${user}/div[@class='users-name']
    ${name_text}=    Get Text    ${parent}
    Log    Name= ${name_text}
END

But I am getting a syntax error that this is not a valid Xpath expression. How can I resolve this? I am using robotframework v7.0 with seleniumlibrary 6.0.

You can log ${user} to see it no longer contains xpath, but internal selenium pointer to an element.

Why not change to something like this?

@{users_list}=    Get WebElements    xpath=//li[contains(@class, 'user_list')]/div[@class='users-name']
FOR    ${user}    IN    @{users_list}
    ${name_text}=    Get Text    ${user}
    Log    Name= ${name_text}
END```
1 Like

Later on I also need to click on ${name_el}. Only ${name_el} is clickable, ${user} is not.

Hmm, you could use Get Element Count and iterate through your original xpath but add [${i}] at the end.

${users_count}=    Get Element Count    xpath=//li[contains(@class, 'user_list')]

FOR    %{i}    IN RANGE    ${users_count} 
    ${name_text}=    Get Text    xpath=(//li[contains(@class, 'user_list')]/div[@class='users-name'])[%{i}]
    Log    Name= ${name_text}
END

Would something like that work for you?

1 Like

Thanks for the suggestion…

I finally figured I could iterate on the users-name instead of the user_list, so I ended up doing something like this

@{users_names_list}=    Get WebElements    xpath=//div[@class='users-name']
FOR    ${i}    IN RANGE    ${users}
	${user_name}=    Get Text    ${users_names_list}[${i}]
	Log	${user_name}
	IF	'${user_name}' == '{my_username}'
		${user_name_el}=	Get WebElement	${users_names_list}[${i}]
		Click Element    ${user_name_el}
		BREAK
	END
END

3 Likes