Selenium 脚本发送键但不满足 'if' 在新打开的选项卡中存在元素的条件

Selenium script sends Keys but won't meet 'if' condition for presence of elements in newly opened tab

我试图让脚本确定元素(在本例中为电子邮件输入 space)是否存在。驱动程序在正确的位置,因为它将密钥发送到正确的位置,但它不会满足下面显示的 if 条件。我也尝试用 try/except 语句和 find_elements() 方法来做到这一点。什么都不管用。未检测到元素 我收到 Timeout 错误可能是因为 expected_condition 语句。如果有帮助,新打开的 Chrome 选项卡是 Microsoft 登录页面。

我的代码:

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") 
       

find_elements 方法没有 return 类型 boolean,这就是为什么您的 if 条件不起作用。它的 return 类型是 List。如果未找到该元素,则它将 return List 大小作为 TimeOut 之后的 0。从文档中,

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

你可以像下面那样做,

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") 

driver.switch_to.window(str(new_tab[-1])) 开始并不是 switch between . Instead you need to use 找到 new window 的理想方式,如下所示:

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)

现在,根据 XPath and/or CssSelector 看来您正在使用 <input> 探测元素form-controltext-box 类名,可能是可点击的元素。在这些情况下,而不是 you need to induce WebDriverWait for the and you can use either of the following :

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")