Selenium 无法将内容提供给iframe中的input字段

Selenium 无法将内容提供给iframe中的input字段

问题描述

我尝试使用以下代码向网站上的一个输入字段提供值:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

if __name__ == '__main__':
  checkLink = "https://www.skatteetaten.no/person/avgifter/bil/eksportere/regn-ut/"

  os.environ['WDM_LOG'] = '0' 
  options = Options()
  options.add_argument("start-maximized")
  options.add_experimental_option("prefs", {"profile.default_content_setting_values.notifications": 1})    
  options.add_experimental_option("excludeSwitches", ["enable-automation"])
  options.add_experimental_option('excludeSwitches', ['enable-logging'])
  options.add_experimental_option('useAutomationExtension', False)
  options.add_argument('--disable-blink-features=AutomationControlled') 
  srv=Service()
  driver = webdriver.Chrome (service=srv, options=options)    
  waitWD = WebDriverWait (driver, 10)           

  driver.get (checkLink)       
  waitWD.until(EC.presence_of_element_located((By.XPATH,'//input[@id="Regnummer"]'))).send_keys("xyz")  

  driver.quit()

但是我总是遇到TimeoutException异常:

$ python test.py
Traceback (most recent call last):
  File "G:\DEV\Fiverr\TRY\csgoenterprise\test.py", line 29, in <module>
    waitWD.until(EC.presence_of_element_located((By.XPATH,'//input[@id="Regnummer"]'))).send_keys("xyz")  
  File "G:\DEV\.venv\selenium\lib\site-packages\selenium\webdriver\support\wait.py", line 95, in until    
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 
Stacktrace:

如何在此输入框中输入值?

解决方案

你的元素位于具有id iFrameResizer0 的iframe中,因此要在输入框中输入内容,你需要先切换到iframe的上下文。

driver.get("https://www.skatteetaten.no/person/avgifter/bil/eksportere/regn-ut/")
driver.maximize_window()

waitWD = WebDriverWait(driver, 10)
waitWD.until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'iFrameResizer0')))
input_field = waitWD.until(EC.presence_of_element_located((By.XPATH, '//input[@id="Regnummer"]'))).send_keys('xyz')
# switch back if you don't need to be left in iframe context
driver.switch_to.default_content()

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程