Wait for element to be clickable using python and Selenium

前端 未结 3 1463
隐瞒了意图╮
隐瞒了意图╮ 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:22

    is there a way to set a default time lag globally, instead of implementing it on each object?

    Yes, that's exactly what setting an Implicit Wait does. The implicit wait is used for the life of the WebDriver.

    example:

    driver.implicitly_wait(10)

    info:

    • https://www.seleniumhq.org/docs/04_webdriver_advanced.jsp#implicit-waits
    0 讨论(0)
  • 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()
      
    0 讨论(0)
  • 2021-01-25 05:31

    I come up with this:

    def myClick(by, desc):
        wait = WebDriverWait(dr, 10)
        by = by.upper()
        if by == 'XPATH':
            wait.until(EC.element_to_be_clickable((By.XPATH, desc))).click()
        if by == 'ID':
            wait.until(EC.element_to_be_clickable((By.ID, desc))).click()
        if by == 'LINK_TEXT':
            wait.until(EC.element_to_be_clickable((By.LINK_TEXT, desc))).click()
    

    with this function, the code:

    driver.find_element_by_link_text('Show Latest Permit').click()
    

    will be

    myClick('link_text', 'Show Latest Permit')
    

    instead.

    I have run a couple weeks with hundreds of elements to click, I have not seen the errors any longer.

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