为什么使用find_element(By ...)而不是find_element_by_ [英] Why use find_element(By...) instead of find_element_by_
问题描述
使用selenium.webdriver.common.by中的By代替常规的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? For example:
driver.find_element_by_id('some_ID')
vs:
from selenium.webdriver.common.by import By
driver.find_element(By.ID, 'some_ID')
推荐答案
根据 documentatio n find_element()
似乎是find_element_by_...()
方法使用的"私有"方法,也可能在
According to documentation 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()
+ By
而不是find_element_by_...()
的原因.
So using Page Object pattern is the reason why you might need find_element()
+ By
instead of find_element_by_...()
.
例如,您有一些变量包含元素的id
值
For example, you have some variable that contains elements' id
value
link_id = "some_id"
,然后用它来定位元素
my_link = driver.find_element_by_id(link_id)
如果出于某些原因从元素中删除了id
属性,则既需要更新选择器,又需要将my_link
中的find_element_by_...()
方法替换为
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
link_class_name = "some_class_name"
my_link = driver.find_element_by_class_name(link_class_name)
如果使用By
,则您的初始定位器可能是
If you use By
, then your initial locator might be
link_locator = (By.ID, "some_id")
,您将元素定位为
my_link = find_element(*link_locator)
如果HTML
源发生更改,您只需将link_locator
更新为
In case of changes in HTML
source you need just to update your link_locator
as
link_locator = (By.CLASS_NAME, "some_class_name")
和my_link
保持完全相同
这篇关于为什么使用find_element(By ...)而不是find_element_by_的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!