Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get All Text in robot framework ?

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

like image 200
velapanur Avatar asked Jun 30 '14 23:06

velapanur


2 Answers

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.

like image 90
ombre42 Avatar answered Sep 22 '22 19:09

ombre42


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}
like image 29
finspin Avatar answered Sep 26 '22 19:09

finspin