Selenium NoSuchElementException无法定位元素:{“method”:“css selector”,“selector”:“[name=”emailAddress“]”“}

2024-04-29 11:56:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试自动登录过程。我正在查找具有名称的元素,但测试失败,响应为“selenium.common.异常.NoSuchElementException:消息:没有此类元素:无法找到元素:{“method”:“css selector”,“selector”:“[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)

Tags: namefromimportself元素titledriverselenium
1条回答
网友
1楼 · 发布于 2024-04-29 11:56:49

这些是常见的情况,您将得到NoSuchElementException

  1. 定位器可能出错
  2. 元素可能在iframe中
  3. 元素可能在另一个窗口中
  4. 元素在脚本尝试查找元素时可能未加载

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

1。定位器可能出错

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

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

2。元素可能存在于iframe中

检查元素是否出现在iframe中而不是父文档中。 enter image description here

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

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

有关详细信息,请查看here。在

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

检查元素是否出现在新的选项卡/窗口中。如果是这样,那么您必须使用switch_to.window切换到选项卡/窗口。在

^{pr2}$

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)

相关问题 更多 >