可视化硒中的焦点和交互

时间:2019-07-15 07:03:54

标签: python selenium

我想查看测试期间页面如何交互,例如当前关注的元素是什么以及交互发生的位置(类似于Cypress UI所做的事情。)

如何最方便地在Selenium for Python中实现这一目标?

1 个答案:

答案 0 :(得分:0)

https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule#Function_to_add_a_stylesheet_rule中的辅助函数的启发,将全局样式表规则添加到我创建的页面add_css.js(在子文件夹helper_js中):

/* global arguments */
(function (rules) {
    var styleEl = document.createElement("style");

    styleEl.classList.add("PART-OF-SELENIUM-TESTING");

    // Append <style> element to <head>
    document.head.appendChild(styleEl);

    // Grab style element's sheet
    var styleSheet = styleEl.sheet;

    for (var i = 0; i < rules.length; i++) {
        var j = 1,
            rule = rules[i],
            selector = rule[0],
            propStr = "";
        // If the second argument of a rule is an array of arrays, correct our variables.
        if (Array.isArray(rule[1][0])) {
            rule = rule[1];
            j = 0;
        }

        for (var pl = rule.length; j < pl; j++) {
            var prop = rule[j];
            propStr += prop[0] + ": " + prop[1] + (prop[2] ? " !important" : "") + ";\n";
        }

        // Insert CSS Rule
        styleSheet.insertRule(selector + "{" + propStr + "}", styleSheet.cssRules.length);
    }

}).apply(null, arguments);

然后我使用以下方法加载并注入到页面中:

import pkgutil
add_css = pkgutil.get_data("helper_js", "add_css.js").decode("utf8")

# ...

driver.execute_script(
    add_css,
    [
        [":active", ["outline", "3px dashed red", True]],
        [":focus", ["outline", "3px dashed yellow", True]],
        [":active:focus", ["outline", "3px dashed orange", True]],
    ]
)

为活动的或具有焦点的元素添加全局样式。