user3925023
user3925023

Reputation: 687

Roboframework Selenium - fidn web element and iterate in nested sub-elements

Hello I have this HTML structure:

<div class="1234" role="article">
    <div class="A">
        <h2 class="B">
            <a class="C" href="https://www.test.it">
            </a>
        </h2>
    </div>
    <div class="X">
        <span class="Y">"some text"
        </span>
    </div>
</div>
<div class="1234" role="article">
    <div class="A">
        <h2 class="B">
            <a class="C" href="https://www.test2.it">
            </a>
        </h2>
    </div>
    <div class="X">
        <span class="Y">"some text2"
        </span>
    </div>
</div>

My goal is to iterate in each Div with role=article, and gather corresponding href and text (i.e. https://www.test.it - "some text" for the first one)

I've created a basic for loop:

${elements}=    Get WebElements     xpath://div[contains(@role, 'article')]
    FOR    ${element}    IN    @{elements}
        Log To Console    ${element.get_attribute('href')}
    END

But i cannot figure it out how to get the sub elements that I need. Any help is more than appreciated. Many thanks

###Update this works for the href, but I'm unable to get the span text ${elements}= Get WebElements xpath://div[contains(@role, 'article')] FOR ${element} IN @{elements} ${sub1}= Set Variable ${element.find_element_by_xpath(".//h2//a[contains(@class, 'C')]")} Log To Console ${sub1.get_attribute('href')} END

Upvotes: 0

Views: 111

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193298

To iterate in each DIV with role="article" and gather corresponding href and text you can use the following Locator Strategies:

  • href:

    ${elements}= Get WebElements xpath://div[contains(@role, 'article')] 
      FOR ${element} IN @{elements} 
          ${sub1}= Set Variable ${element.find_element_by_xpath(".//h2/a[@class='C']")} 
          Log To Console ${sub1.get_attribute('href')} 
      END
    
  • text:

    ${elements}= Get WebElements xpath://div[contains(@role, 'article')] 
      FOR ${element} IN @{elements} 
          ${sub1}= Set Variable ${element.find_element_by_xpath(".//div[@class='X']/span[@class='Y']")} 
          Log To Console ${sub1.get_attribute('innerHTML')} 
      END
    

Upvotes: -1

Related Questions