简体   繁体   English

为什么使用 find_element(By...) 而不是 find_element_by_

[英]Why use find_element(By...) instead of find_element_by_

What's the purpose and upside of using By from selenium.webdriver.common.by instead of instead of the normal find_element_by_... methods?使用 By from selenium.webdriver.common.by 而不是普通的 find_element_by_... 方法的目的和好处是什么? For example:例如:

driver.find_element_by_id('some_ID')

vs:对比:

from selenium.webdriver.common.by import By
driver.find_element(By.ID, 'some_ID')

According to documentatio n find_element() seem to be kind of " private " method that is used by find_element_by_...() methods and also might be used in Page Object 根据文档, find_element()似乎是find_element_by_...()方法使用的“ 私有 ”方法,也可能在Page Object中使用

So using Page Object pattern is the reason why you might need find_element() + By instead of find_element_by_...() . 因此,使用页面对象模式是您可能需要find_element() + By而不是find_element_by_...()

For example, you have some variable that contains elements' id value 例如,您有一些包含元素id值的变量

link_id = "some_id"

and you use it to locate element as 然后用它来定位元素为

my_link = driver.find_element_by_id(link_id)

If for some reason id attribute was removed from element, you need both to update selector and replace find_element_by_...() method in my_link as 如果由于某种原因id属性从元素去掉,你既需要更新选择和替换find_element_by_...()的方法my_link作为

link_class_name = "some_class_name"
my_link = driver.find_element_by_class_name(link_class_name)

If you use By , then your initial locator might be 如果您使用By ,那么您的初始定位符可能是

link_locator = (By.ID, "some_id")

and you locate your element as 然后将元素定位为

my_link = find_element(*link_locator)

In case of changes in HTML source you need just to update your link_locator as 如果HTML源代码发生更改,您只需将link_locator更新为

link_locator = (By.CLASS_NAME, "some_class_name")

and my_link remains exactly the same my_link保持完全相同

Like above answer.就像上面的答案。 I get the deprecated message when using find_element_by_id etc. So best way should be by using find_element() .我在使用find_element_by_id等时收到已弃用的消息。所以最好的方法应该是使用find_element()

Both of these methods are from the RemoteWebDriver class. 这两种方法都来自RemoteWebDriver类。

findElement(By.id()) requires you to created your own By.id instance.
findElementById(String) is a helper function that will generate the By.id
instance for you.

It comes down to providing you with the flexibility to choose what you want to keep track of in your tests/framework. 归根结底,是您可以灵活地选择要在测试/框架中跟踪的内容。 Do you want to track locators as Strings? 您想将定位符跟踪为字符串吗? Do you want to track locators as By objects? 您是否要按“对象”跟踪定位器?

同样在新的python版本中, find_element_by_...()被删除了,所以只需使用find_element() + By

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM