Search code examples
pythonseleniumexpected-condition

Selenium Expected Conditions - waiting for an xpath to become available - I dont know how to type it in my code


I'm Scott, still somewhat new to python, still trying to figure out how it all works...LOL

I have a script that logs into a website for work, does some clicking on a few objects, and then pulls a report based on those settings that were clicked

the problem I am having is that sometimes the server is busy, so things take different amounts of time to appear... some items are not clickable until drop down menus have been activated...etc so I need the script to wait for the xpath of each object to become available

I dont understand the explicit wait usage

currently code is UGLY with my bad usage of time.sleep and other various things..

Code Included below...but heres an example of what I need it to wait for I need to Insert Explicit waits that will wait for the element to become available

Thanks ahead of time for all your help I've solved quite a few of my other issues in the script with the help of this forum

#Close City Arrow
print('Close City')
loc_arrow2 = (browser.find_element_by_xpath('//*[@id="rddlLocation_Arrow"]'))
loc_arrow2.click()

time.sleep(2)

#Category Button
print ('Category Button')
CategoryRadioBtn = browser.find_element_by_id('rbnSearchCategory')
CategoryRadioBtn.click()
WebDriverWait(browser,20)

time.sleep(2)

#L1 Set to 3d_blah_blah_blah
print('L1 Set to 3d_blah_blah_blah')

loc_L1 = (browser.find_element_by_xpath('//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]'))
loc_L1.click()


time.sleep(2)

loc_L2 = (browser.find_element_by_xpath('//*[@id="ctlCategorySelect1_ddlCategory1_Input"]'))
loc_L2.clear()
loc_L2.send_keys('3')
loc_L2.send_keys(u'\ue007')


Solution

  • Lets take the below line as sample to explain the EC (Expected Condition).

    loc_L1 = (browser.find_element_by_xpath('//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]'))
    

    You have to add below imports to work with Explicit wait using EC.

    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    

    And here how you have to write the explicit wait

    WebDriverWait(driver,waitTimeInSec).until(EC.presence_of_element_located((By.strategy,"xpath_goes_here")))
    # Below is the example
    loc_L1 = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,'//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]')))
     # if you want to wait for the element to be clickable then use below.
    WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]')))
    

    In case you get the ElementNotInteractable exception, then use js click as shown below.

    driver.execute_script("arguments[0].click()",loc_L1)