Issue
I am writing a code in selenium to login to a website and check the response to determine whether we are successfully logged in or not. I wrote the following code to achieve it
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
def handle_response(self):
try:
WebDriverWait(self.driver, 3).until(EC.presence_of_element_located((By.XPATH, "//button[@class='s-btn s-btn-primary s-btn--block enterEmailComponent-button']"))) # 2 fa login
return True
except TimeoutException:
try:
WebDriverWait(self.driver, 3).until(EC.presence_of_element_located((By.XPATH, "//input[@id='search-autocomplete-input']"))) # normal login
return True
except TimeoutException:
return False
The following code works fine though it first checks for first element
(2 fa login) then use try & expect
block to check 2nd element
(normail-login) which takes too much time.
I was just curious if i could make both the checks simultaneously
and return the value from the one that succeeds.
Solution
Yes, you can try to use any
function:
def handle_response(self):
try:
WebDriverWait(self.driver, 3).until(
lambda driver: any(
EC.presence_of_element_located((By.XPATH, "//button[@class='s-btn s-btn-primary s-btn--block enterEmailComponent-button']"))(driver),
EC.presence_of_element_located((By.XPATH, "//input[@id='search-autocomplete-input']"))(driver)
)
)
return True
except TimeoutException:
return False
It will return True
when one of the conditions is ok.
Answered By - lukos06
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.