使用 webdriver 查找元素的最佳和最快方法是什么?By.XPath 或 By.ID 还是其他?为什么? [英] Which is the best and fastest way to find the element using webdriver? By.XPath or By.ID or anything else? And why?

查看:21
本文介绍了使用 webdriver 查找元素的最佳和最快方法是什么?By.XPath 或 By.ID 还是其他?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 webdriver 查找元素的最佳和最快方法是什么?By.XPath 或 By.ID 还是其他?为什么?

Which is the best and fastest way to find the element using webdriver? By.XPath or By.ID or anything else? And why?

我在很多地方都读到 XPath 是合适的候选者,但找不到准确的理由.

I have read at many places that XPath is the right candidate but just could not find the accurate reason for that.

推荐答案

通过 ID 查找元素通常是最快的选择,因为从根本上讲,它最终会调用 document.getElementById(),经过很多浏览器的优化.

Finding elements by ID is usually going to be the fastest option, because at its root, it eventually calls down to document.getElementById(), which is optimized by many browsers.

通过 XPath 查找元素对于使用非常复杂的选择器查找元素很有用,并且是最灵活的选择策略,但它可能会非常慢,尤其是在 IE 中.在 IE 6、7 或 8 中,通过 XPath 查找可能比在 Firefox 中查找要慢一个数量级.IE 没有提供原生 XPath-over-HTML 解决方案,因此项目必须使用 JavaScript XPath 实现,而旧版 IE 中的 JavaScript 引擎确实慢得多.

Finding elements by XPath is useful for finding elements using very complex selectors, and is the most flexible selection strategy, but it has the potential to be very slow, particularly in IE. In IE 6, 7, or 8, finding by XPath can be an order of magnitude slower than doing the same in Firefox. IE provides no native XPath-over-HTML solution, so the project must use a JavaScript XPath implementation, and the JavaScript engine in legacy versions of IE really is that much slower.

如果您需要使用复杂的选择器查找元素,我通常建议尽可能使用 CSS 选择器.它不像 XPath 那样灵活,但可以涵盖许多相同的情况,而不会像 XPath 那样对 IE 表现出极端的性能损失.

If you have a need to find an element using a complex selector, I usually recommend using CSS Selectors, if possible. It's not quite as flexible as XPath, but will cover many of the same cases, without exhibiting the extreme performance penalty on IE that XPath can.

这篇关于使用 webdriver 查找元素的最佳和最快方法是什么?By.XPath 或 By.ID 还是其他?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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