如何遍历WebElement并在Robot Framework中获取新的WebElement

时间:2020-03-27 00:16:56

标签: python-3.x selenium robotframework

我正在尝试使用hrefhtml列表中获得Robot Framework keywords属性。例如,假设html代码

<ul class="my-list">
<li class="my-listitem"><a href="...">...</li>
...
<li class="my-listitem"><a href="...">...</li>
</ul>

我尝试使用关键字WebElementWebElementsfor loop失败。我该怎么办?

这是我的MWE

*** Test Cases ***
@{a tags} =  Create List
@{href attr} = Create List
@{li items} = Get WebElements    class:my-listitem

FOR ${li}  IN  @{li items}
    ${a tag} =  Get WebElement    tag:a
    Append To List    @{a tags}    ${a tag}
END

FOR ${a tag}  IN  @{a tags}
    ${attr} =  Get Element Attribute    css:my-listitem   href
    Append To List    @{href attr}    ${attr}
END

谢谢。

2 个答案:

答案 0 :(得分:1)

hrefa元素的属性,而不是li的属性,因此您需要将它们作为目标。获取所有此类元素的引用,然后在循环中获取其href

${the a-s}=     Get WebElements    xpath=//li[@class='my-listitem']/a    # by targeting the correct element, the list is a reference to all such "a" elements
${all href}=    Create List
FOR    ${el}    IN    @{the a-s}   # loop over each of them
    ${value}=     Get Element Attribute    ${el}    href   # get the individual href
    Append To List    ${all href}  ${value}   # and store it in a result list
END
Log To Console    ${all href}

答案 1 :(得分:0)

这是一个可能的解决方案(未经测试):

@{my_list}=    Get WebElements    xpath=//li[@class='my-listitem']
FOR    ${element}    IN    @{my_list}
    ${attr}=    Get Element Attribute    ${element}    href
    Log    ${attr}    html=True
END
相关问题