硒-找不到这种元素

时间:2019-11-16 10:29:46

标签: python selenium selenium-webdriver

尝试使用selenium + python和以下代码为snow dev实例设置自动登录是我尝试的代码段,但由于某些奇怪的原因,每次它给我一个错误“找不到此类元素”或超时异常,因为我尝试了不同的设置,尽管该元素在html页面上非常可用。

我是selenium / python的新手,因此非常感谢您的帮助/建议。谢谢,

明确等待

wait = WebDriverWait(driver, 10)
uName = wait.until(ec.visibility_of_element_located((By.ID, "user_name")))
# un = wait.until(ec.presence_of_element_located((By.NAME, 'user_name')))
uName.send_keys("admin")

引发超时异常

 File "C:/Users/Administrator/Users/Desktop/PySelenium/snow.py", line 21, in <module>
    uName = wait.until(ec.visibility_of_element_located((By.ID, "user_name")))
  File "C:\Users\Administrator\Users\Desktop\PySelenium\venv\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

有睡眠时间

from selenium import webdriver
import time

driver = webdriver.Chrome(executable_path="C:\\Users\\Administrator\\Downloads\\chromedriver_win32\\chromedriver.exe")
driver.get("https://dev91011.service-now.com/")
time.sleep(120)
uName = driver.find_element_by_id("user_name")
uName.send_keys("admin")

抛出无法定位元素的错误

File "C:\Users\Administrator\Users\Desktop\PySelenium\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="user_name"]"}
  (Session info: chrome=78.0.3904.87)

雪页中的定位器

<div><label class="control-label" for="user_name">User name</label><input type="text" class="form-control" id="user_name" name="user_name" value="" autocomplete="off"></div>

1 个答案:

答案 0 :(得分:2)

您要查找的项目位于iframe中。您需要先将驱动程序的上下文切换到框架。

from selenium import webdriver
import time

driver = webdriver.Chrome(executable_path="C:\\Users\\Administrator\\Downloads\\chromedriver_win32\\chromedriver.exe")
driver.get("https://dev91011.service-now.com/")
time.sleep(120)
frame = driver.find_element_by_css_selector('#gsft_main')
driver.switch_to.frame(frame)
uName = driver.find_element_by_css_selector('input[id="user_name"]')
uName.send_keys("admin")