仅单击可见元素selenium webdriverjs [英] click only visible element selenium webdriverjs

查看:93
本文介绍了仅单击可见元素selenium webdriverjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个div,如下所示

I have multiple div like below

<div class="one">send Message</div>

<div class="one">send Message</div>

<div class="one">send Message</div>

我有一个网页,上面有类似于上面的发送消息按钮,一次只能看到一个按钮,另外两个按钮通过一些javascript代码被隐藏了,例如,如果第二个按钮可见,我应该只能单击该元素.但是在我的硒代码中,它试图单击第一个隐藏的div并失败了

I have a web page where there is send Message buttons like above, in which only one button is visible at a time.Other two buttons are hidden via some javascript codes.So for example if 2nd button is visible , I should be able to click only that element.But in my selenium code , its trying to click first hidden div and its failing

 driver.findElements(by.className(".one")).then((els) => {
            var element = els[index];
            element.click();
        });

所以基本上我想将下面的javascript代码转换为Selenium nodejs代码,如果有人可以帮助我的话

So basically I wanna convert below javascript code to Selenium nodejs code,If some one guide me that will be helpful

var all = document.getElementsByTagName("*");

for (var i = 0, max = all.length; i < max; i++) {
    if (isHidden(all[i]))
        // hidden
    else 
        // visible
}

function isHidden(el) {
    var style = window.getComputedStyle(el);
    return ((style.display === 'none') || (style.visibility === 'hidden'))
}

推荐答案

是否要单击可见的按钮(就代码而言,基本上是div)?

Do you want to click the button ( basically a div as far as code is concerned ) which is visible ?

如果这是您的主要议程,那么您编写的代码将找不到所需的元素.当您通过元素的类名而不是可见性来选择元素时.

If that is your main agenda, then the code you've written will fail to find desired element. As you are selecting the element by it's classname not its visibility.

您的代码将找到所有匹配的类元素.因为它是一个基本的元素选择器,并且所有按钮都具有相同的类,所以它们基本上呈现在页面上.

Your code will find all the matched class element. As it's a basic element selector and all your buttons have the same class, so they are basically rendered on the page.

driver.findElements(by.className(".one")).then((els) => {
        for(var key in els){
             var element = els[key];
             if(element.isDisplayed()){ //if visible element
               element.click();            
             }
        }
    });

此处的关键是检查您要单击的元素在页面上是否可见.

The Key here is to check if the element you are trying to click is visible on the page.

通过为目标按钮提供唯一的类.某些类,例如"clickable"或"active".因此,使用Css选择器选择目标元素将是更优化的解决方案.此处的关键是使目标元素具有唯一性,以便于识别.

By giving a unique class to the target button. Some class for eg 'clickable' or 'active'. So it will be a more optimized solution to select the target element using the Css selector. The Key here is to give uniqueness to your target element to be more identifiable.

这篇关于仅单击可见元素selenium webdriverjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆