How does starred expression works when using with find_element() method

  • def enter_text_textbox(self, locator, text):
        ele = self.driver.find_element(*locator)
  "# Entering text in Textbox.")
            return True
        except NoSuchElementException:
            return False

    Here is a method enter_text_textbox which accepts locator and some text as parameters. I passed locator as something like this: self.email_field = (By.XPATH, "//input[@id='email']")

    When I tried to get into this(self.driver.find_element(*locator)) method, it displayedenter image description here

    As from the image the methods contains parameters of ID only.

    By running the test script(not displayed here), it worked perfectly fine. I want to know how does this method know if this locator is made by XPATH or ID or CSS i.e. How the starred expression works?

  • First of all, a really nice question which allowed me to think a lot and I was expecting someone (with more python experience) to answer this.

    Coming to the answer, a couple of things to note here:

    To locate an element, you can directly call the find_element_by_*, directly which internally calls find_element api. It is also suggested to use the explicit find_element_by_*.

    If you look at the find_element api signature,

    find_element(self, by=By.ID, value=None)

    the default initialized value for by is By.ID. So don't get confused with the by type you are sending and the default value. When you deep dive, you will see, if the by type is ID, NAME, TAG_NAME, CLASS_NAME, the by type is converted to CSS_SELECTOR and the value is also converted to its corresponding css_selector_value. After that, If the by type is anything else apart from the mentioned above, it just executes that command.

    elf.execute(Command.FIND_ELEMENT, {
                'using': by,
                'value': value})['value']

    The second part of the question, 'The starred argument':

    Take a look at this for a better understanding of *args and **kwargs in python:

    Youtube Video

    (basically arguments can be both 'packed' and 'unpacked' using the star and double star syntax)

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2