![](/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.