【问题标题】:Selenium NoSuchElementException - Unable to locate element: {"method":"css selector","selector":"[name="emailAddress"]"}Selenium NoSuchElementException - 无法定位元素:{"method":"css selector","selector":"[name="emailAddress"]"}
【发布时间】:2019-11-25 17:41:51
【问题描述】:

我正在尝试自动化登录过程。我正在寻找一个具有名称但测试失败的元素,响应是“selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{“方法”:“css选择器”,“选择器” :"[name="emailAddress"] "}" 我的代码有什么问题?

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class MainTests(unittest.TestCase):
   def setUp(self):
       self.driver = webdriver.Chrome(executable_path=r"C:\TestFiles\chromedriver.exe")

   def test_demo_login(self):
       driver = self.driver
       driver.get('http://localhost:8000/login')
       title = driver.title
       print(title)
       assert 'Calculator' == title


       element = driver.find_element_by_name("emailAddress")
       element.send_keys("name123@gmail.com")

       time.sleep(30)

【问题讨论】:

  • 请发布您的html源代码

标签: python css selenium automated-tests selenium-chromedriver


【解决方案1】:

这些是您会得到 NoSuchElementException

的常见情况
  1. 定位器可能有误
  2. 元素可能存在于 iframe 中
  3. 元素可能在另一个窗口中
  4. 脚本尝试查找元素时可能未加载元素

现在,让我们看看如何处理这些情况。

1.定位器可能有误

检查browser devtool/console 中的定位器是否正确。

如果您的脚本中的定位器不正确,请更新定位器。如果正确,则转到下面的下一步。

2。元素可能在 iframe 中

检查元素是否存在于 iframe 中而不是父文档中。

如果您看到元素在 iframe 中,那么您应该切换到 iframe,然后再找到该元素并与之交互。 (记得在完成 iframe 元素的步骤后切换回父文档)

driver.switch_to.frame("frame_id or frame_name")

您可以查看here 了解更多信息。

3.元素可能在另一个窗口中

检查元素是否存在于新选项卡/窗口中。如果是这种情况,那么您必须使用 switch_to.window 切换到选项卡/窗口。

# switch to the latest window
driver.switch_to.window(driver.window_handles[-1])

# perform the operations
# switch back to parent window
driver.switch_to.window(driver.window_handles[0])

4.脚本尝试查找元素时可能未加载元素

如果以上都不是错误的来源,这是我们看到 NoSuchElementException 的最常见原因。您可以使用 WebDriverWait 显式等待来处理此问题,如下所示。

您需要以下导入来处理显式等待。

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

脚本:

# lets say the "//input[@name='q']" is the xpath of the element
element = WebDriverWait(driver,30).until(EC.presence_of_element_located((By.XPATH,"//input[@name='q']")))
# now script will wait unit the element is present max of 30 sec
# you can perform the operation either using the element returned in above step or normal find_element strategy
element.send_keys("I am on the page now")

您也可以使用隐式等待,如下所示。

driver.implicitly_wait(30)

【讨论】:

  • 原来“元素可能在脚本尝试查找元素时未加载”Self.driver.implicitly_wait(30) 完成了这项工作。感谢您的帮助
  • 如果您认为问题已解决,请点击左侧投票按钮下方的空心复选标记接受答案。
  • 为什么你编辑你的 cmets 添加我应用的解决方案,我写过这个解决方案?
  • 人们有时可能不会阅读 cmets,所以我只是想确保答案中存在解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-25
  • 2022-06-23
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多