Wait for element to be clickable using python and Selenium

我是研究僧i 提交于 2020-12-13 10:34:52

问题


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.

However, when there are hundreds of objects, is there a way to set a default time lag globally, instead of implementing it on each object?

The click() action should have a conditional wait time?


回答1:


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()
    



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/56380889/wait-for-element-to-be-clickable-using-python-and-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!