Shi*_*ya_ 2 css python selenium automated-tests selenium-chromedriver
我正在尝试自动化登录过程。我正在寻找一个具有名称的元素,但测试失败并且响应是“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)
Run Code Online (Sandbox Code Playgroud)
这些是您将获得的常见情况 NoSuchElementException
现在,让我们看看如何处理这些情况。
1. 定位器可能有误
在浏览器 devtool/console 中检查您的定位器是否正确。
如果脚本中的定位器不正确,请更新定位器。如果正确,则转到下面的下一步。
2.元素可能在iframe中
如果您看到元素在 iframe 中,那么您应该切换到 iframe,然后再找到该元素并与之交互。(记住在完成 iframe 元素上的步骤后切换回父文档)
driver.switch_to.frame("frame_id or frame_name")
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看更多信息。
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])
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
脚本:
# 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")
Run Code Online (Sandbox Code Playgroud)
您还可以使用隐式等待,如下所示。
driver.implicitly_wait(30)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4104 次 |
| 最近记录: |