Warm tip: This article is reproduced from serverfault.com, please click

Find if next sibling exist

发布于 2020-12-08 20:24:31

I try to write some robot test cases and I got stuck. I need to extract some links from a page. The links are stored inside an <li> tag which is also inside an <ul>. The problem is that after I extract the first link I need to go to the next <li> (the first <li> next sibling) but how can I find if there is a next sibling without getting an error or the application stop. I know, I can use Element Should Contain keyword but in case if it not contain I get an error.
I want to do something like this:

if next sibling exist  do something
else go do something else

The html should look like this.

<ul id="top_menu" role="menubar" class="">
    <li class="menu_accordion_section" id="cat_1">
        <a href="some-exampe"> </a>
    </li>
    <li class="menu_accordion_section" id="cat_2">
        <a href="some-exampe"> </a>
    </li>
</ul>
Questioner
tibi
Viewed
11
PDHide 2021-01-08 10:29:53

There is direct message, you can use execute script to create a varaible.

so i created a keyword

  Validate child element exists

it takes two argument parent(Webelement) and child(Xpath) to search for child inside the parent.

  Validate child element exists    ${parent}    ./h3

Assuming parent xpath to as : //ul[@id="top_menu"] , the above code will search for equalent xpath //ul[@id="top_menu"]/./h3 note taht context is parent and not root

so this will be equalent to xpath

*** Test Cases ***
Google Search
    [Tags]    you    probably    do    not    have    this    many    tags    in    real    life
    Wait Until Element Is Visible  CSS=[id="introduction-container"]
    ${parent}=    Get webelement    xpath=//*[@id="introduction-container"]
    ${result}=    Validate child element exists    ${parent}    ./h3   
    Should Be True     ${result}

    
*** Keywords ***
Validate child element exists 
    [Arguments]    ${parent}   ${child} 
    ${child}=    Execute Javascript    return window.document.evaluate( arguments[1], arguments[0], null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;     ARGUMENTS    ${parent}    ${child}
    [Return]    ${child}