Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

python - 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? For example:

driver.find_element_by_id('some_ID')

vs:

from selenium.webdriver.common.by import By
driver.find_element(By.ID, 'some_ID')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

So using Page Object pattern is the reason why you might need find_element() + By instead of find_element_by_...().

For example, you have some variable that contains elements' id value

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

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

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

link_locator = (By.CLASS_NAME, "some_class_name")

and my_link remains exactly the same


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...