Search code examples
listxpathrobotframework

Turning an Xpath into a list variable and use For loop


I'm very new to robot framework. This question is about creating a list variable using Xpath.

I'm trying to write a FOR LOOP in robot in order to print all items that appear on a search result page. Here is what I've done so far:

  1. I tried to declare a list variable using Xpath:
    @{product}         //div[contains(@class,'ProductCard__TitleMaxLines')]

This Xpath has the number of repetitions the same as the number of items on the page, e.g. 20, so I assume that this list will contain 20 members. --> Is this how it works?

  1. I created a For loop:
    ${index}        Set variable        1
    For     ${product}  in      @{related_product}
            Exit for loop if    ${index} > 20
            Log to console      ${product}
            ${index}        Evaluate        ${index}+1

    End          

For this, I assume that it will take the first product found on the Xpath to be index=1, and the next index=2, and so on.

That's all I've done so far. Please advise if this works correctly or if there is another way that is better and more typical.


Solution

  • I think your question is, you have similar kind of xpath around 20 times in the webpage. If my understanding is correct, you should use the Get Webelements keyword from Selenium Library.

    @{product}     Get Webelements    //div[contains(@class,'ProductCard__TitleMaxLines')]
    

    The above line will create the list of webelements which having the same xpath