Home > Software engineering >  Multiple conditions using python selenium webdriver wait-until
Multiple conditions using python selenium webdriver wait-until

Time:10-04

I almost sure that there are few simple solutions for that, but.. i'm clicking an element of web page and one of more than 2 different pages can appear after it. Than i need to click one of the specific elements for each kind of result pages.
If i had 2 variants i could use TRY and EXCEPT WebDriverWait.until structures.

lesson = driver.find_element_by_xpath('//input[@class = "playButton"]')
lesson.click()
try:
    WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH, '//div[@class = "cursor-hover"]')))
    start_b = driver.find_element_by_xpath('//div[@class = "cursor-hover"]')
    start_b.click()
except:
    WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.XPATH, '//div[@class = "cursor-hover2"]')))
    start_g = driver.find_element_by_xpath('//div[@class = "cursor-hover2"]')
    start_g.click()

This structure works perfect. If there is no first element - the second one is clicked. So what can i use to successfully identify the only element of 5 or more?

CodePudding user response:

If i understand correctly you need to tweak your xpath a little like this could solve your problem, make sure xpath is unique for page.

lesson = driver.find_element_by_xpath('//input[@class = "playButton"]')
lesson.click()

WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH, '//div[@class = "cursor-hover"]|//div[@class = "cursor-hover2"]')))

start_b = driver.find_element_by_xpath('//div[@class = "cursor-hover"]|//div[@class = "cursor-hover2"]')
start_b.click()

Or to make it more simple you can also just click with wait.

WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH, '//div[@class = "cursor-hover"]|//div[@class = "cursor-hover2"]'))).click()

if using xpath with pipe delimiter doesn't suite and you want to stick to exception then i would recommend you to identify the page first then add wait otherwise adding webdriverwait for 5 pages will take too long to get to fifth page so instead

try something link

if driver.find_element_by_xpath('//some title or specific element of page'):
    WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH, 'xpath for that page'))).click()

CodePudding user response:

Probably having a list of possible xpaths and iterating through them would be the easiest solution.

# possible xpaths depending on what page will be opened afterwards
possible_xpaths = ['//div[@class = "cursor-hover1"]', '//*[@class="something else"]', ...]

for xpath in possible_xpaths:
    try:
        WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH, xpath)))
        element = driver.find_element_by_xpath(xpath)
        element.click()
        break # found the correct element
    except:
        pass # continue to try the next xpath
  • Related