![](/img/trans.png)
[英]selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".ui flu~"}
[英]Selenium NoSuchElementException - Unable to locate element: {“method”:“css selector”,“selector”:“[name=”emailAddress“]”}
我正在尝试自动化登录过程。 我正在寻找一个具有名称的元素,但测试失败,并且响应为“ 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)
这些是常见的情况,您会收到NoSuchElementException
现在,让我们看看如何处理这些情况。
1.定位器可能有误
在浏览器devtool / console中检查您的定位器是否正确。
如果您的脚本中的定位器不正确,请更新定位器。 如果正确,请移至下面的下一步。
2.元素可能在iframe中
如果您看到该元素在iframe中,则应在找到该元素并与其进行交互之前切换到iframe。 (完成iframe元素上的步骤后,请记住切换回父文档)
driver.switch_to.frame("frame_id or frame_name")
您可以在此处查看更多信息。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.