在Java中使用Selenium快速获取每个WebElement的类属性 [英] Quickly get class attribute of every WebElement with Selenium in Java

查看:554
本文介绍了在Java中使用Selenium快速获取每个WebElement的类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找使用硒快速获取页面上每个WebElement的class属性.目前,我正在执行以下操作:

I'm looking to get the class attribute of every WebElement on the page quickly with selenium. Currently, I'm doing the following:

allElements = new ArrayList<WebElement>(m_webDriver.findElements(By.cssSelector("*")));

for (WebElement element : allElements) {
    String className = element.getAttribute("class");
}

此过程非常慢,在包含500个元素的页面上花费长达30秒的时间.我尝试并行化getAttribute调用,这是该方法中最慢的部分,但是没有提高速度.这使我相信,每次对getAttribute的调用都是在获取信息,而不是将其存储在本地.

This process is incredibly slow, taking upwards of thirty seconds on a page with 500 elements. I've tried parallelizing the getAttribute call, which is the slowest part of the method, but there was no speed increase. This leads me to believe that every call to getAttribute is fetching information instead of storing it locally.

是否有一种更快或可并行化的方式来做到这一点?

Is there a faster or parallelizable way to do this?

推荐答案

问题是,您不能让硒发送批处理getAttribute()调用多个元素.这是我遇到的类似问题调查了-这是关于使isDisplayed()可用于多个元素,而无需对列表中的每个元素进行JSON Wire协议请求:

The problem is, you cannot make selenium send batch getAttribute() calls for multiple elements. Here is a similar problem I've looked into - it is about making isDisplayed() work for multiple elements without making JSON Wire protocol requests for every element in a list:

但是,相对于此isDisplayed()问题,在这里我们可以执行javascript并可靠地获取页面上每个元素的类属性值,类似这样的内容可以帮助您入门:

But, as opposed to this isDisplayed() problem, here we can execute javascript and reliably get the class attribute values for every element on a page, something like this to get you started:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("var result = []; " +
"var all = document.getElementsByTagName('*'); " +
"for (var i=0, max=all.length; i < max; i++) { " +
"    result.push({'tag': all[i].tagName, 'class': all[i].getAttribute('class')}); " +
"} " +
" return result; ");

这篇关于在Java中使用Selenium快速获取每个WebElement的类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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