Consider the following source code,
<div id="groupContainer" class="XXXXXX">
<ul id="GroupContactListWrapper" class="list-wrapper">
<li class="contactNameItemContainer">
<div class="contactNameItem">
<span class="name">Name1</span>
</div>
</li>
<li class="contactNameItemContainer">
<div class="contactNameItem">
<span class="name">Name2</span>
</div>
</li>
</ul>
</div>
How do i retreive the two names (Name1,Name2) in a list variable ? I tried the following xpath for a "Get Text" keyword, but only returns the first one.
//div[@id='groupContainer']//li[@class='contactNameItemContainer']//span
Please suggest
You could iterate over the elements as below:
${xpath}= Set Variable //div[@id='groupContainer']//li[@class='contactNameItemContainer']//span
${count}= Get Matching Xpath Count ${xpath}
${names}= Create List
:FOR ${i} IN RANGE 1 ${count} + 1
\ ${name}= Get Text xpath=(${xpath})[${i}]
\ Append To List ${names} ${name}
This works but is rather slow when there are many matches.
You could extend Selenium2Library
and write your own keyword for this purpose. Save the following as Selenium2LibraryExt.py
from Selenium2Library import Selenium2Library
class Selenium2LibraryExt(Selenium2Library):
def get_all_texts(self, locator):
"""Returns the text value of elements identified by `locator`.
See `introduction` for details about locating elements.
"""
return self._get_all_texts(locator)
def _get_all_texts(self, locator):
elements = self._element_find(locator, False, True)
texts = []
for element in elements:
if element is not None:
texts.append(element.text)
return texts if texts else None
Then you can use your new Get All Texts
keyword in your tests like this:
*** Settings ***
library Selenium2LibraryExt
*** Test Cases ***
Get All Texts Test
Open Browser http://www.example.com chrome
@{texts} Get All Texts css=.name
Log Many ${texts}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With