python - Selenium:Python 无法从 elif 中找到元素

标签 python selenium selenium-webdriver selenium-chromedriver

我正在使用 if-elif 条件。当元素处于第一个条件时可以找到它们,但 Selenium 只是挂起并且当元素位于 elif 时找不到该元素。有什么想法吗?

这是我正在使用的代码:

if (driver.find_elements_by_xpath(("//*[contains(text, 'Hello Automation User')]"))):
    print ("Test Passed")
elif (driver.find_elements_by_class_name('error')):
    print ("Test Failed: Username and Password combination mismatch")
else:
    print("Test failed")

仅供引用,我正在使用 chromedriver

最佳答案

不要捕获异常,而是像这样尝试:

if len(driver.find_elements_by_xpath(("//*[contains(text, 'Hello Automation User')]"))) > 0:
  # pass
elif len(driver.find_elements_by_class_name('error')) > 0:
  # fail
else:
  # fail

请注意,driver.find_elements_by_xpath 返回一个数组,因此它始终是真实的(就像您所拥有的那样)

关于python - Selenium:Python 无法从 elif 中找到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54974819/

相关文章:

ruby - 使用 Capybara/Selenium/RSpec 抑制奇怪的输出

python - Webdriver/Selenium : How to find element when it has no class name, id,还是css选择器?

java - 如何使用 Java 在 Selenium WebDriver 中执行鼠标悬停功能?

python - 在 any() 语句中迭代一个小列表是否更快?

python - 如何在 Python 中创建 Socket.io 客户端以与 Sails 服务器通信

java - 使用 Webdriver 在网页中查找输入标签,并 driver.findElements 抛出异常。为什么?

image - Selenium - 检查图像是否显示在页面上

python socket recv() 和信号

python - 将 matplotlib 图例条目集中在不完整/未填充的行中?

ruby-on-rails - ruby rails : Overwrite instance variable on Selenium tests