Why use find_element(By…) instead of find_element_by_

前端 未结 2 678
刺人心
刺人心 2020-12-07 02:22

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:

drive         


        
相关标签:
2条回答
  • 2020-12-07 02:35

    Both of these methods are from the RemoteWebDriver class.

    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?

    0 讨论(0)
  • 2020-12-07 02:48

    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

    0 讨论(0)
提交回复
热议问题