代码之家  ›  专栏  ›  技术社区  ›  nhrcpt

如何在Robot Framework或Python Selenium中验证特定元素或文本在监视器上是否可见

  •  2
  • nhrcpt  · 技术社区  · 8 年前

    我需要测试一下,一旦我点击一个链接,网页的一个特定部分就可以在监视器上看到。考虑以下Wikipedia代码:

    Open Browser    https://en.wikipedia.org/wiki/Selenium_(software)    Chrome
    Page should contain    Selenium Remote Control
    Click Element    //*[@href="#Selenium_Remote_Control"]
    Sleep    3s
    Close All Browsers
    

    正如所料,当单击元素时,我可以直观地看到Wikipedia页面中的“Selenium Remote Control”部分出现在我的监视器屏幕上。我可以验证页面上是否有该节或文本,并且html代码应该能够处理“跳转到href”部分。但为了确保它在我们的应用程序和不同的浏览器实例上正常工作,我们希望有一种自动方法,能够在点击链接后,实际验证“Selenium Remote Control”部分是否在监视器屏幕上可见。

    1 回复  |  直到 8 年前
        1
  •  2
  •   A. Kootstra    8 年前

    您给出的示例确实是一个长页面,其中所讨论的元素加载到DOM中,但在浏览器视图端口中不可见。但是,当使用 ... should be visible 关键字只查看DOM,从这个角度来看,它是可见的。只是无法查看。

    如果一个可见元素确实是可查看的,那么有一些小javascript函数可以进行评估。关于这个 Go Make Things article 这个 isInViewPort(elem) 找到函数。

    IsInViewPort。js公司

    /*
     * Obtained from: https://gomakethings.com/how-to-test-if-an-element-is-in-the-viewport-with-vanilla-javascript/
     */
    var isInViewport = function (elem) {
        var bounding = elem.getBoundingClientRect();
        return (
            bounding.top >= 0 &&
            bounding.left >= 0 &&
            bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    };
    

    在Robot脚本中,我们可以继续获取元素,然后使用自定义关键字将其传递给此函数: Element Should Be In View 返回一个 boolean 当一个元素为true而哪个元素为false时。

    是视图中的元素。机器人

    *** Settings ***
    Library    Selenium2Library
    Library    OperatingSystem    
    
    
    *** Test Cases ***
    Element Should Be in View Test
        [Documentation]
        ...    Test to validate that an element isn't view-able and then is view-able. 
        Open Browser    https://en.wikipedia.org/wiki/Selenium_(software)    Chrome
    
        ${elem}    Get Webelement    xpath=//*[@id="Selenium_Remote_Control"]
        ${bool}    Element Should Be In View    ${elem}
        Should Not Be True    ${bool}
    
        Click Element    //*[@href="#Selenium_Remote_Control"]
    
        ${elem}    Get Webelement    xpath=//*[@id="Selenium_Remote_Control"]
        ${bool}    Element Should Be In View    ${elem}
        Should Be True    ${bool}
    
        [Teardown]    Close All Browsers
    
    *** Keywords ***
    Element Should Be In View
        [Documentation]
        ...    Partially Inspired by: https://stackoverflow.com/a/28709012/6152737
        [Arguments]    ${element}
        ${s2l}=     Get Library Instance    Selenium2Library
        ${js}=      Get File    IsInViewport.js    
        ${visible}=    Call Method    
        ...                ${s2l._current_browser()}    
        ...                execute_script    ${js} return isInViewport(arguments[0]);    ${element}
        [Return]    ${visible}
    

    当视图更改时,即由于单击了链接,则需要再次检索元素。否则,不会返回旧状态。