웹사이트 검색

셀레늄 findElement 및 findElements 예제


웹 페이지와 상호 작용할 때마다 사용자가 웹 요소를 찾아야 합니다. 우리는 일반적으로 WebDriver를 사용하여 웹 응용 프로그램을 자동화할 계획일 때마다 페이지에서 HTML 요소를 찾는 것으로 시작합니다. Selenium WebDriver는 요소를 식별하기 위한 두 가지 방법인 findElementfindElements를 정의합니다.

  1. findElement: 이 명령은 웹 페이지 내에서 웹 요소를 고유하게 식별하는 데 사용됩니다.
  2. findElements: 이 명령은 웹 페이지 내에서 웹 요소 목록을 고유하게 식별하는 데 사용됩니다.

ID, 이름, 클래스 이름, LinkText, PartialLinkText, TagName 및 XPath와 같이 웹 페이지 내에서 웹 요소를 고유하게 식별하는 여러 가지 방법이 있습니다.

findElement와 findElements 메소드의 차이점

FindElement() 메서드:

  • 이 명령은 웹 페이지의 단일 요소에 액세스하는 데 사용됩니다
  • 지정된 로케이터의 첫 번째 일치 요소의 개체를 반환합니다.
  • 요소를 식별하지 못하면 NoSuchElementException이 발생합니다.

FindElements() 메서드:

  • 이 명령은 웹 페이지 내의 웹 요소 목록을 고유하게 식별하는 데 사용됩니다.
  • 이 방법의 사용은 매우 제한적입니다
  • 요소가 페이지에 없으면 빈 목록과 함께 값을 반환합니다

셀레늄 findElement 명령

요소 찾기 명령은 By 개체를 매개 변수로 사용하고 WebElement 유형의 개체를 반환합니다. 개체별은 ID, 이름, 클래스 이름, 링크 텍스트, XPath 등과 같은 다양한 로케이터 전략과 함께 사용할 수 있습니다.

FindElement 명령 구문

WebElement elementName = driver.findElement(By.LocatorStrategy("LocatorValue"));

로케이터 전략은 다음 값 중 하나일 수 있습니다.

  • ID
  • 이름
  • 클래스 이름
  • 태그 이름
  • 링크 텍스트
  • 부분 링크 텍스트
  • XPath

로케이터 값은 웹 요소를 식별할 수 있는 고유한 값입니다. ID 또는 이름과 같은 특정 속성을 사용하여 웹 요소를 고유하게 식별하는 것은 개발자와 테스터의 핵심 책임입니다. 예:

WebElement login= driver.findElement(By.linkText("Login"));

셀레늄 findElements 명령

Selenium findElements 명령은 By object를 매개 변수로 사용하고 웹 요소 목록을 반환합니다. 지정된 로케이터 전략 및 로케이터 값을 사용하여 요소를 찾지 못한 경우 빈 목록을 반환합니다.

FindElements 명령 구문

List<WebElement> elementName = driver.findElements(By.LocatorStrategy("LocatorValue"));

예:

List<WebElement> listOfElements = driver.findElements(By.xpath("//div"));

Selenium findElement 명령을 사용하는 방법

다음 애플리케이션은 데모 목적으로 사용됩니다: https://www.irctc.co.in/nget/user-registration 시나리오

  1. AUT에 대한 https://www.irctc.co.in/nget/user-registration 열기
  2. 라디오 버튼을 찾아서 클릭

package com.journaldev.selenium.findelement;

import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.chrome.ChromeDriver;

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

     System.setProperty("webdriver.chrome.driver","D:\\Drivers\\chromedriver.exe");
     WebDriver driver= new ChromeDriver();
     driver.manage().window.maximize():
     driver.get(:"https://www.irctc.co.in/nget/user-registration");

//Find the radio button for "Male" by using ID and click on it
driver.findElement(By.id("M")).click();

       } 
}

Selenium findElements 명령을 사용하는 방법

다음 애플리케이션은 데모용 https://www.irctc.co.in/nget/user-registration 시나리오에 사용됩니다.

  1. AUT에 대한 https://www.irctc.co.in/nget/user-registration 열기
  2. 라디오 버튼의 텍스트를 찾아 콘솔에 인쇄


package com.journaldev.selenium.findelements;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumFindElements {

	public static void main(String[] args) {

	System.setProperty("webdriver.chrome.driver","D:\\Drivers\\chromedriver.exe");
	WebDriver driver= new ChromeDriver();
        driver.get("https://www.irctc.co.in/nget/user-registration");
        List<WebElement> elements = driver.findElements(By.id("M"));
        System.out.println("Number of elements:" +elements.size());

       for(int i=0; i<elements.size(); i++){
       System.out.println("Radio button text:" + elements.get(i).getAttribute("value"));
	}
     }
}

Selenium 로케이터에 액세스하기 위한 다중 전략

Selenium Webdriver는 findElement(By.) 메소드를 사용하여 웹 요소를 참조합니다. findElement 메소드는 <\By\>로 알려진 로케이터 객체를 사용합니다. 요구 사항에 따라 사용할 수 있는 다양한 "By\ 전략이 있습니다.

1. 아이디로

명령: driver.findElement(By.id(<요소 ID>)) 예: id로 입력 요소를 찾는 Java 예제 코드

WebElement user = driver.findElement(By.id("JournalDev"));

2. 이름으로

명령: driver.findElement(By.name()) 예: 이름으로 입력 요소를 찾는 Java 예제 코드

WebElement user = driver.findElement(By.name("JournalDev"));

3. 클래스 이름별

명령: driver.findElement(By.className()) 예: className으로 입력 요소를 찾는 Java 예제 코드입니다.

WebElement user = driver.findElement(By.className("JournalDev"));

4. LinkText로

명령: driver.findElement(By.linkText(<링크 텍스트>)) 예: JournalDev-1 JournalDev-2 요소 일치 링크 또는 부분 링크 텍스트를 찾기 위한 Java 예제 코드:

WebElement link = driver.findElement(By.linkText("JournalDev-1"));
WebElement link = driver.findElement(By.partialLinkText("JournalDev-2"));

5. CssSelector 사용

명령: driver.findElement(By.cssSelector()) 예: 링크 또는 부분 링크 텍스트와 일치하는 요소를 찾기 위한 Java 예제 코드:

WebElement emailText = driver.findElement(By.cssSelector("input#email"));

6. XPath 사용

명령: driver.findElement(By.xpath()) XPath용 Java 예제 코드:

// Absolute path
WebElement item = driver.findElement(By.xpath("html/head/body/table/tr/td"));

// Relative path
WebElement item = driver.findElement(By.xpath("//input"));

// Finding elements using indexes
WebElement item = driver.findElement(By.xpath("//input[2]"));
```****