繁体   English   中英

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

[英]How to check if element is displayed on website?

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

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

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

它应该是:

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

希望能帮助到你!

你很接近。 要定位元素,您必须为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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM