iFrame을 처리하는 방법 Selenium 웹드라이버: switchTo()

⚡ 스마트 요약

iFrame을 처리하는 방법 Selenium WebDriver는 테스터가 페이지 내 HTML 프레임을 제어하는 ​​방법을 보여주며, 식별, 컨텍스트 전환, 중첩 처리 및 안정성 기법을 다룹니다.

  • 🖼️ iFrame 기본 사항: 하나의 HTML 문서를 다른 HTML 문서 안에 삽입합니다.
  • 🔍 식별 : 개발자 도구를 사용하거나 findElements(By.tagName)을 사용하세요.
  • 🔁 전환 대상: 인덱스, 이름, ID 또는 웹 요소별로 전환하세요.
  • 🪜 중첩됨: parentFrame과 defaultContent가 다시 위로 이동합니다.
  • ⚠️ 안정: 예외 발생을 방지하려면 switchTo를 하기 전에 잠시 기다리세요.
  • 🤖 AI 도우미: AI는 강력한 iFrame 로케이터를 생성합니다.

iFrame을 처리하는 방법 Selenium 웹드라이버

iFrame 입력 Selenium 웹드라이버

iFrame 입력 Selenium 웹드라이버 다른 웹 페이지에 포함된 웹 페이지 또는 인라인 프레임이거나 다른 HTML 문서 내에 포함된 HTML 문서입니다. iframe은 광고와 같은 다른 소스의 콘텐츠를 웹 페이지에 추가하는 데 자주 사용됩니다. iframe은 다음과 같이 정의됩니다.iframe이> 태그.

iFrame을 식별하는 방법

페이지를 보거나 Firebug를 검사하는 것만으로는 프레임을 감지할 수 없습니다.

아래 이미지를 살펴보세요. 표시되는 광고는 Iframe입니다. Firebug를 사용하여 검사하는 것만으로는 찾을 수 없고 인식할 수도 없습니다. 따라서 질문은 iframe을 어떻게 식별할 수 있느냐는 것입니다.

Iframe 식별
다음을 사용하여 iframe을 식별하는 방법 Selenium 웹드라이버

우리는 프레임을 식별할 수 있습니다. Selenium 아래에 주어진 방법을 사용하여:

  • 요소를 마우스 오른쪽 버튼으로 클릭하고 'This Frame'과 같은 옵션을 찾으면 iframe입니다.(위 다이어그램 참조)
  • 페이지를 마우스 오른쪽 버튼으로 클릭하고 '페이지 소스 보기'를 클릭한 후 'iframe'으로 검색하세요. 'iframe'이 포함된 태그 이름이 있으면 iframe으로 구성된 페이지를 의미합니다.

위의 다이어그램에서 '이 프레임' 옵션은 마우스 오른쪽 버튼을 클릭하면 사용할 수 있으므로 이제 iframe임을 확신합니다.

아래 스니펫을 사용하여 총 iframe 수를 식별할 수도 있습니다.

Int size = driver.findElements(By.tagName("iframe")).size();

프레임을 처리하는 방법 Selenium WebDriver 명령 사용

기본적으로 요소를 전환하고 프레임을 처리할 수 있습니다. Selenium 3가지 방법을 사용합니다.

  • 인덱스별
  • 이름 또는 ID로
  • 웹 요소별

방법 1: 인덱스별로 프레임으로 전환

인덱스는 프레임 처리를 위한 속성 중 하나입니다. Selenium 이를 통해 우리는 그것으로 전환할 수 있습니다.

iframe의 인덱스는 '0'으로 시작합니다.

페이지에 100개의 프레임이 있다고 가정하면 다음 프레임으로 전환할 수 있습니다. Selenium 인덱스를 사용하여.

  • driver.switchTo().frame(0);
  • driver.switchTo().frame(1);

방법 2: 이름 또는 ID로 프레임으로 전환

이름과 ID는 프레임을 처리하기 위한 속성입니다. Selenium 이를 통해 iframe으로 전환할 수 있습니다.

  • driver.switchTo().frame("iframe1");
  • driver.switchTo().frame("id of the element");

ID를 통해 iframe으로 전환하는 예:

Web Element로 프레임에

우리는 아래를 통해 이 iframe에 접근할 수 있습니다. URL: https://demo.guru99.com/test/guru99home/

프레임 처리 Selenium WebDriver 명령 사용

iframe을 직접 클릭하는 것은 불가능합니다. xpath iframe이기 때문입니다. 먼저 프레임으로 전환한 다음 xpath를 사용하여 클릭할 수 있습니다.

단계 1)

WebDriver driver = new FirefoxDriver();

driver.get("https://demo.guru99.com/test/guru99home/");

driver.manage().window().maximize();

  • 우리는 Firefox 운전사.
  • iframe을 구성하는 "guru99" 사이트로 이동합니다.
  • 창을 최대화했습니다.

단계 2)

driver.switchTo().frame("a077aa5e");
  • 이 단계에서는 Firebug를 통해 검사하여 iframe의 ID를 찾아야 합니다.
  • 그런 다음 ID를 통해 iframe으로 전환합니다.

단계 3)

driver.findElement(By.xpath("html/body/a/img")).click();
  • 여기서는 클릭할 요소의 xpath를 찾아야 합니다.
  • 위에 표시된 웹 드라이버 명령을 사용하여 요소를 클릭합니다.

전체 코드는 다음과 같습니다.

public class SwitchToFrame_ID {
public static void main(String[] args) {

		WebDriver driver = new FirefoxDriver(); //navigates to the Browser
	    driver.get("https://demo.guru99.com/test/guru99home/"); 
	       // navigates to the page consisting an iframe

	       driver.manage().window().maximize();
	       driver.switchTo().frame("a077aa5e"); //switching the frame by ID

			System.out.println("********We are switch to the iframe*******");
     		driver.findElement(By.xpath("html/body/a/img")).click();
  		    //Clicks the iframe
       
  			System.out.println("*********We are done***************");
      }
}		

출력:

브라우저는 위의 iframe으로 구성된 페이지로 이동하여 iframe을 클릭합니다.

방법 3: 웹 요소로 프레임으로 전환

웹 요소를 사용하여 iframe으로 전환할 수도 있습니다.

  • driver.switchTo().frame(WebElement);

메인 프레임으로 다시 전환하는 방법

iframe에서 나와야 합니다.

상위 프레임으로 다시 이동하려면 switchTo().parentFrame()을 사용할 수 있고, 기본(또는 가장 상위) 프레임으로 돌아가려면 switchTo().defaultContent()를 사용할 수 있습니다.

	    driver.switchTo().parentFrame();
	    driver.switchTo().defaultContent();

ID 또는 웹 요소를 사용하여 전환할 수 없는 경우 프레임을 전환하는 방법:

페이지에 100개의 프레임이 있고 사용 가능한 ID가 없다고 가정하면, 이 경우 어떤 iframe 필수 요소가 로드되고 있는지 알 수 없습니다. (프레임의 인덱스를 모르는 경우입니다.) 또한).

위의 우려에 대한 해결책은 요소가 로드되는 iframe의 인덱스를 찾은 다음 해당 인덱스를 통해 iframe으로 전환해야 합니다.

다음은 아래 스니펫을 사용하여 요소가 로드되는 프레임의 인덱스를 찾는 단계입니다.

단계 1)

WebDriver driver = new FirefoxDriver();
driver.get("https://demo.guru99.com/test/guru99home/");
driver.manage().window().maximize();
  • 초기화 Firefox 운전사.
  • iframe을 구성하는 "guru99" 사이트로 이동합니다.
  • 창을 최대화했습니다.

단계 2)

int size = driver.findElements(By.tagName("iframe")).size();
  • 위 코드는 'iframe'이라는 태그 이름을 사용하여 페이지 내에 존재하는 총 iframe 수를 찾습니다.

단계 3)

목적 이 단계는 iframe의 색인을 찾는 것입니다.

for(int i=0; i<=size; i++){
	driver.switchTo().frame(i);
	int total=driver.findElements(By.xpath("html/body/a/img")).size();
	System.out.println(total);
	    driver.switchTo().defaultContent();}

위의 "forloop"는 페이지의 모든 iframe을 반복하고 필요한 iframe이 발견되면 '1'을 인쇄하고 그렇지 않으면 '0'을 반환합니다.

3단계까지의 전체 코드는 다음과 같습니다.

public class IndexOfIframe {
public static void main(String[] args) {
	    WebDriver driver = new FirefoxDriver();
	    driver.get("https://demo.guru99.com/test/guru99home/");  
	    driver.manage().window().maximize();
	    //driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
	    int size = driver.findElements(By.tagName("iframe")).size();

	    for(int i=0; i<=size; i++){
		driver.switchTo().frame(i);
		int total=driver.findElements(By.xpath("html/body/a/img")).size();
		System.out.println(total);
	    driver.switchTo().defaultContent();}}}

이 프로그램을 실행하면 아래와 같이 출력됩니다.

출력:

1
0
0
0	
0
0

출력을 확인하면 일련의 0과 1을 찾을 수 있습니다.

  • 출력에서 요소가 로드되는 프레임의 인덱스인 '1'을 찾을 수 있습니다.
  • 0에서 1을 찾으면 iframe의 인덱스는 '1'으로 시작하므로st위치이면 인덱스는 0입니다.
  • 1개 중 3개를 찾으면rd 장소, 인덱스는 2입니다.

인덱스를 찾으면 for 루프를 주석 처리할 수 있습니다.

단계 4)

driver.switchTo().frame(0);
  • 요소의 인덱스를 찾으면 위 명령을 사용하여 프레임을 전환할 수 있습니다.
  • drivers.switchTo().frame(3단계에서 찾은 인덱스);

단계 5)

driver.findElement(By.xpath("html/body/a/img")).click();
  • 위 코드는 iframe 또는 iframe의 요소를 클릭합니다.

따라서 전체 코드는 아래와 같습니다.

public class SwitchToframe   {
public static void main(String[] args) throws NoSuchElementException{
	    WebDriver driver = new FirefoxDriver();
	    driver.get("https://demo.guru99.com/test/guru99home/");  
	    driver.manage().window().maximize();
	    //int size = driver.findElements(By.tagName("iframe")).size();
	
	/*for(int i=0; i<=size; i++){
	    driver.switchTo().frame(i);
	    int total=driver.findElements(By.xpath("html/body/a/img")).size();
		System.out.println(total);
	    driver.switchTo().defaultContent(); //switching back from the iframe
	 }*/
	            
		//Commented the code for finding the index of the element
	    driver.switchTo().frame(0); //Switching to the frame
		System.out.println("********We are switched to the iframe*******");
		driver.findElement(By.xpath("html/body/a/img")).click();
		
		//Clicking the element in line with Advertisement
	    System.out.println("*********We are done***************");
	        }
	    }

출력:

브라우저는 위의 iframe으로 구성된 페이지로 이동하여 iframe을 클릭합니다.

중첩된 프레임의 개념 Selenium

아래 이미지와 같이 내부에 두 개의 프레임이 있고 우리의 요구 사항은 외부 프레임과 내부 프레임에 텍스트를 인쇄한다고 가정해 보겠습니다.

중첩된 프레임의 경우,

  • 먼저 iframe의 인덱스 또는 ID를 사용하여 외부 프레임으로 전환해야 합니다.
  • 외부 프레임으로 전환하면 외부 프레임 내부의 총 iframe 수를 찾을 수 있습니다.
  • 알려진 방법 중 하나를 사용하여 내부 프레임으로 전환할 수 있습니다.

프레임 밖으로 나갈 때에는 안쪽 프레임에서 먼저 들어갔다가 바깥쪽 프레임에 들어간 순서와 동일한 순서로 빠져나와야 합니다.

위 중첩 프레임의 HTML 코드는 아래와 같습니다.

중첩된 프레임의 개념 Selenium

위의 HTML 코드는 중첩된 iframe이 있음을 나타내는 다른 iframe 태그 내의 iframe 태그(녹색으로 강조 표시됨)를 명확하게 설명합니다.

다음은 외부 프레임으로 전환하고 외부 프레임에 텍스트를 인쇄하는 단계입니다.

단계 1)

	WebDriver driver=new FirefoxDriver();
	    driver.get("Url");
	    driver.manage().window().maximize();
	    driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
	    int size = driver.findElements(By.tagName("iframe")).size();
	    System.out.println("Total Frames --" + size);
	    
		// prints the total number of frames 
		driver.switchTo().frame(0); // Switching the Outer Frame    		
	    System.out.println (driver.findElement(By.xpath("xpath of the outer ">element ")).getText());
  • 외부 프레임으로 전환합니다.
  • 외부 프레임에 텍스트를 인쇄합니다.

외부 프레임으로 전환하면 외부 프레임 내부에 내부 프레임이 있는지 알아야 합니다.

단계 2)

size = driver.findElements(By.tagName("iframe")).size();
    // prints the total number of frames inside outer frame           
    System.out.println("Total Frames --" + size);
  • 외부 프레임 내부의 총 iframe 수를 찾습니다.
  • 크기가 '0'인 경우 프레임 내부에 내부 프레임이 없습니다.

단계 3)

driver.switchTo().frame(0); // Switching to innerframe
System.out.println(driver.findElement(By.xpath("xpath of the inner ">element ")).getText());
  • 내부 프레임으로 전환
  • 내부 프레임에 텍스트를 인쇄합니다.

전체 코드는 다음과 같습니다.

public class FramesInsideFrames {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
	    driver.get("Url");
	    driver.manage().window().maximize();
	    driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);

	    int size = driver.findElements(By.tagName("iframe")).size();
	    System.out.println("Total Frames --" + size);
               
		// prints the total number of frames 
		driver.switchTo().frame(0); // Switching the Outer Frame    		
	    System.out.println (driver.findElement(By.xpath("xpath of the outer ">element ")).getText());

		//Printing the text in outer frame
		size = driver.findElements(By.tagName("iframe")).size();
	    // prints the total number of frames inside outer frame           
                                                                                                          
	    System.out.println("Total Frames --" + size);
	    driver.switchTo().frame(0); // Switching to innerframe
	    System.out.println(driver.findElement(By.xpath("xpath of the inner ">element ")).getText());
		
		//Printing the text in inner frame
		driver.switchTo().defaultContent();
	}
}

산출:

위 코드의 출력은 내부 프레임과 외부 프레임의 텍스트를 인쇄합니다.

자주 묻는 질문

프레임은 더 이상 사용되지 않습니다. iFrame은 페이지 내부에 단일 문서를 삽입하는 데 사용됩니다.

AI는 위치 정보 제공자를 제안하고 불안정한 인덱스를 자체적으로 복구합니다.

네. AI가 DOM을 검사하고 적절한 switchTo를 삽입합니다.

switchTo().defaultContent() 또는 parentFrame()을 사용하세요.

iFrame이 없거나 오래된 상태입니다. 명시적인 대기 시간을 추가하세요.

driver.findElements(By.tagName(“iframe”)).size().

switchTo는 작동합니다. 일부 JavaScriptExecutor 호출이 실패할 수 있습니다.

기초는 하루, 중첩 프레임은 1~2주 정도 소요됩니다.

이 게시물을 요약하면 다음과 같습니다.