selenium positioning find_element method

Since learning selenium , the first thing that comes to mind when it comes to element positioning is find_element_by_xxx.

But today when I was studying, I discovered that there is another method find_element, without the following by.

So I tried to click into the source code to see it, but failed (I don’t know if it is because vscode does not support it).

So I searched for relevant content on the Internet, and it seems that this method is indeed feasible. I posted the suspected source code as follows:

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

          """

          根据策略和定位器找到给定的元素。

   

          :使用方法:

              element = driver.find_element(By.ID, 'foo')

   

          :rtype: WebElement

          """

          if self.w3c:

              if by == By.ID:

                  by = By.CSS_SELECTOR

                  value = '[id="%s"]' % value

              elif by == By.TAG_NAME:

                  by = By.CSS_SELECTOR

              elif by == By.CLASS_NAME:

                  by = By.CSS_SELECTOR

                  value = ".%s" % value

              elif by == By.NAME:

                  by = By.CSS_SELECTOR

                  value = '[name="%s"]' % value

          return self.execute(Command.FIND_ELEMENT, {

              'using': by,

              'value': value})['value']

Try to use this method for page encapsulation, passing in a tuple, the first element is the positioning key, and the second element is the positioning value.

  class Page:

   

      url = None

      driver = None

   

      @classmethod

      def cls_element(cls, loc: tuple):

          return cls.driver.find_element(*loc)

   

      def element(self, loc: tuple):

          """

          定位元素的方法

          :param loc:

          :return:

          """

          return self.driver.find_element(*loc)

   

      def elements(self, loc: tuple):

          """

          定位一组元素或多个元素

          :param loc:

          :return:

          """

          return self.driver.find_elements(*loc)

 

Finally: The complete software testing video tutorial below has been compiled and uploaded. Friends who need it can get it by themselves [guaranteed 100% free]

Software Testing Interview Document

We must study to find a high-paying job. The following interview questions are from the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.

Guess you like

Origin blog.csdn.net/wx17343624830/article/details/132831699