Wait for element to be clickable using python and Selenium

前端 未结 3 1465
隐瞒了意图╮
隐瞒了意图╮ 2021-01-25 04:54

There are ways to wait for an object e.g. a button to be clickable in selenium python. I use time.sleep() and/or WebDriverWait...until, it works fine.<

3条回答
  •  旧巷少年郎
    2021-01-25 05:28

    You can do a few things...

    1. Define a global default wait time and then use that in each wait you create.

      default_wait_time = 10 # seconds
      ...
      wait = WebDriverWait(driver, default_wait_time)
      
    2. Inside of a method where you will use the wait several times, you can instantiate a wait, store it in a variable, and then reuse it.

      def my_method(self):
          wait = WebDriverWait(driver, 10)
          wait.until(EC.visibility_of_element_located((By.ID, "username")).send_keys("username")
          wait.until(EC.visibility_of_element_located((By.ID, "password")).send_keys("password")
          wait.until(EC.element_to_be_clickable((By.ID, "login")).click()
      
    3. Define a default WebDriverWait instance and then just repeatedly use that.

      Note: if you are or will run your script(s) in parallel, you need to be very careful with this approach because an instance of WebDriverWait is tied to a specific driver.

      # some global location
      wait = WebDriverWait(driver, 10)
      ...
      # in your script, page object, helper method, etc.
      wait.until(EC.element_to_be_clickable((By.ID, "login")).click()
      

提交回复
热议问题