如何检查元素是否显示在网站上?

时间:2019-12-14 16:40:27

标签: python selenium xpath css-selectors webdriverwait

我正在尝试创建登录测试,因此第一步是,如果用户成功登录脚本,则应在登录后的主页中查找元素。

我的问题是,如果无法登录python的用户抛出NoSuchElementException异常,而不会转到其他异常。

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

def login_test(self):
    driver_location = 'D:\\chromedriver.exe'
    os.environ["webdriver.chrome.driver"] = driver_location
    driver = webdriver.Chrome(driver_location)
    driver.maximize_window()
    driver.implicitly_wait(3)
    driver.get("http://www.example.com/")

prof_icon= driver.find_element_by_xpath("//button[contains(@class,'button')]")
if prof_icon.is_displayed():
    print("Success: logged in!")
else:
    print("Failure: Unable to login!")

我也尝试过:

 prof_icon= driver.find_element_by_xpath("//button[contains(@class,'button')]")
 try:   
      if prof_icon.is_displayed():
        print("Success: logged in!")
 except NoSuchElementException :
        print("Failure: Unable to login")

但是脚本总是崩溃并引发异常。我只需要它来打印消息,以防万一该元素未显示。

2 个答案:

答案 0 :(得分:0)

应该是:

except NoSuchElementException:  #correct name of exception
    print("Failure: Unable to login")

您可以查看元素是否存在,如果不存在,则显示“失败:无法登录”。 注意.find_elements_*中的复数“ s”。

prof_icon = driver.find_elements_by_xpath("//button[contains(@class,'button')]")
if len(prof_icon) > 0
    print("Success: logged in!")
else:
    print("Failure: Unable to login")

希望有帮助!

答案 1 :(得分:0)

你很近。要找到要为visibility_of_element_located()生成 WebDriverWait 的元素,可以使用以下Locator Strategies之一:

  • 使用CSS_SELECTOR

    try:   
        WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "button.button")))
        print("Success: logged in!")
    except TimeoutException:
        print("Failure: Unable to login")
    
  • 使用XPATH

    try:   
        WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//button[contains(@class,'button')]")))
        print("Success: logged in!")
    except TimeoutException:
        print("Failure: Unable to login")
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException