0

I am trying to check the existence of two elements(A,B) on a website.What I need is to click on the element A if it exists if not go ahead and look for B and click on it if it exists. Below is part of my sample code.

try:
        abc= WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#rso > div > div > div:nth-child(1) > div > div > h3 > a")))
    except NoSuchElementException:
        continue
    except TimeoutException:
        continue
    else:
        element.click()


try:
        element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#rso > div > div > div:nth-child(1) > div > div > h3 > a")))
    except NoSuchElementException:
        continue
    except TimeoutException:
        continue
    else:
        abc.click()
        time.sleep(randint(1, 15))


print('Process completed successfully')

The issue that I face is that the code only looks for the first element and doesn't go ahead into the next try. Any advice would be great.

2 Answers 2

1

Try below to click first element and in case it's not found - click second:

try:
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "first.element"))).click()
except TimeoutException:
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "second.element"))).click()

P.S. Replace "first.element", "second.element" with real CSS selectors

If both elements might not be present on page:

try:
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "first.element"))).click()
except TimeoutException:
    try:
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "second.element"))).click()
    except TimeoutException:
        print("Both elements not found")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a ton Andersson :)
0
wait = WebDriverWait(driver, 30)
try:
    elements = wait.until(
        EC.presence_of_all_elements_located(
            (By.CSS_SELECTOR, 'first.element'
                              'second.element')
        )
    )
    if elements[0].tag_name == 'first.element':
        print("login fail")
    elif elements[0].tag_name == 'second.element':
        print("login")
except:
    print("Both elements not found")

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.