I am trying to have the script determine whether an element (in this case the email input space) is present or not. The driver is in the right place as it sends Keys to the right place, but it won't meet the if
condition shown below. I tried to do this with try/except
statement and with a find_elements()
method too. Nothing works. The element is not detected I get a Timeout
error probably because of the expected_condition
statement. The newly opened Chrome tab is a Microsoft Login page if this can help.
My code:
def check_need_to_sign_in():
new_tab = driver.window_handles
driver.switch_to.window(str(new_tab[-1]))
print(driver.current_url)
element_present = EC.presence_of_element_located((By.XPATH, "//input[@class='form-control ltr_override input ext-input text-box ext-text-box']")) # WON'T DETECT ELEMENT):
WebDriverWait(driver, timeout).until(element_present)
if driver.find_elements(By.CSS_SELECTOR, "input.form-control ltr_override input ext-input text-box ext-text-box"): # WON'T DETECT ELEMENT)
print("Element exists")
sign_in()
else:
print("Element does not exist")
CodePudding user response:
To start with driver.switch_to.window(str(new_tab[-1]))
isn't the ideal way to switch between window_handles. Instead you need to use List Comprehension to locate the new window as follows:
window_before = driver.current_window_handle
print("First Window Handle is : %s" %window_before)
driver.execute_script("window.open('','_blank');")
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
windows_after = driver.window_handles
new_window = [x for x in windows_after if x != window_before][0]
driver.switch_to.window(new_window)
Now, as per the XPath and/or CssSelector it seems you are probing an <input>
element with form-control and text-box classnames and possibly it's a clickable element. In those cases, instead of presence_of_element_located()
you need to induce WebDriverWait for the element_to_be_clickable()
and you can use either of the following Locator Strategies:
try:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='form-control ltr_override input ext-input text-box ext-text-box']")))
print("Clickable element was found")
except TimeoutException:
print("Clickable element wasn't found")
CodePudding user response:
The find_elements
method doesn't have the return type as boolean
that's why your if
condition is not working. It's return type is List
. If the element is not found then it will return the List
size as 0
after TimeOut
. From documentation,
This method will return as soon as there are more than 0 items in the found collection, or will return an empty list if the
timeout
is reached.@see org.openqa.selenium.WebDriver.Timeouts
You can do like below,
elements = driver.find_elements(By.CSS_SELECTOR, "input.form-control ltr_override input ext-input text-box ext-text-box")
if elements.size > 0 :
print("Element exists")
sign_in()
else:
print("Element does not exist")