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

How to check if element is displayed on website?

我正在尝试创建一个登录测试,所以第一步是如果用户成功登录脚本应该在主页 post 登录中查找一个元素。

我的问题是,如果用户无法登录 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")

但是脚本总是崩溃并抛出异常。我只需要它在 else 中打印消息,以防元素未显示。

应该是:

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

您可以查看元素是否存在,如果不存在则打印 "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")

希望对您有所帮助!

你很接近。要定位您必须为 visibility_of_element_located() 引入 WebDriverWait 的元素,您可以使用以下任一项 :

  • 使用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