programing

Selenium WebDriver를 사용하여 요소가 존재하는지 테스트합니다.

prostudy 2022. 6. 29. 20:29
반응형

Selenium WebDriver를 사용하여 요소가 존재하는지 테스트합니다.

요소가 존재하는지 테스트하는 방법이 있나요?모든 findElement 메서드는 예외로 종료되지만, 이는 요소가 존재하지 않고 문제가 없을 수 있기 때문에 테스트에 불합격하지 않기 때문에 예외가 해결책이 될 수 없습니다.

다음 게시물을 찾았습니다.Selenium c# 웹 드라이버: 요소가 존재할 때까지 기다립니다.그러나 이것은 C#용이며, 저는 그다지 능숙하지 않습니다.코드를 자바어로 번역할 수 있는 사람이 있나요?죄송합니다, 이클립스에서 시도해 봤는데 자바 코드로 바로 전달이 안 돼요.

코드는 다음과 같습니다.

public static class WebDriverExtensions{
    public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds){

        if (timeoutInSeconds > 0){
            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
            return wait.Until(drv => drv.FindElement(by));
        }

        return driver.FindElement(by);
    }
}

findElementsfindElement.

findElements예외 대신 일치하는 요소를 찾을 수 없는 경우 빈 목록을 반환합니다.

요소가 존재하는지 확인하려면 다음과 같이 하십시오.

Boolean isPresent = driver.findElements(By.yourLocator).size() > 0

하나 이상의 요소가 발견되면 true를 반환하고 존재하지 않으면 false를 반환합니다.

공식 문서에서는 다음 방법을 권장합니다.

findElement를 사용하여 존재하지 않는 요소를 찾고 findElements(By)를 사용하여 길이 제로 응답을 강조하지 마십시오.

단순히 요소를 검색하여 다음과 같은 요소가 존재하는지 확인하는 개인 메서드는 어떻습니까?

private boolean existsElement(String id) {
    try {
        driver.findElement(By.id(id));
    } catch (NoSuchElementException e) {
        return false;
    }
    return true;
}

이것은 꽤 쉬울 것이고 그 일을 할 수 있을 것이다.

편집: 더 나아가서By elementLocator파라미터로서 id 이외의 방법으로 요소를 찾으려는 경우의 문제를 해소합니다.

Java에서 동작하는 것을 알 수 있었습니다.

WebDriverWait waiter = new WebDriverWait(driver, 5000);
waiter.until( ExpectedConditions.presenceOfElementLocated(by) );
driver.FindElement(by);
public static WebElement FindElement(WebDriver driver, By by, int timeoutInSeconds)
{
    WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
    wait.until( ExpectedConditions.presenceOfElementLocated(by) ); //throws a timeout exception if element not present after waiting <timeoutInSeconds> seconds
    return driver.findElement(by);
}

저도 같은 문제가 있었어요.사용자의 권한 수준에 따라 링크, 버튼 및 기타 요소가 페이지에 표시되지 않습니다.내 스위트룸의 일부는 없어져야 할 요소들이 없어지는 것을 테스트하고 있었다.이걸 알아내는데 몇 시간이나 걸렸어요나는 마침내 완벽한 해결책을 찾았다.

그러면 브라우저에 지정된 모든 요소를 검색하도록 지시합니다., 「 」가 0즉, 사양에 근거한 요소를 찾을 수 없습니다.그리고 코드에게 if 스테이트먼트를 실행하여 발견되지 않았음을 알립니다.

은 이이에에 this this this this this에 있습니다.C#은 「」로 할 Java하지만 너무 힘들지는 않을 거야

public void verifyPermission(string link)
{
    IList<IWebElement> adminPermissions = driver.FindElements(By.CssSelector(link));
    if (adminPermissions.Count == 0)
    {
        Console.WriteLine("User's permission properly hidden");
    }
}

또한 시험에 필요한 것에 따라 선택할 수 있는 다른 길이 있습니다.

다음 스니펫은 페이지에 특정 요소가 존재하는지 확인합니다.요소의 존재에 따라 테스트를 실행합니다.

요소가 존재하여 페이지에 표시되는 경우,console.write알려주시고 넘어가세요.해당 요소가 존재하면 필요한 테스트를 실행할 수 없기 때문에 셋업이 필요한 주된 이유가 됩니다.

요소가 존재하지 않고 페이지에 표시되지 않는 경우.다른 하나는 에 있습니다.그렇지 않으면 테스트를 실행합니다.

IList<IWebElement> deviceNotFound = driver.FindElements(By.CssSelector("CSS LINK GOES HERE"));
//if the element specified above results in more than 0 elements and is displayed on page execute the following, otherwise execute whats in the else statement
if (deviceNotFound.Count > 0 && deviceNotFound[0].Displayed){
    //script to execute if element is found
} else {
    //Test script goes here.
}

OP에 대한 답변이 좀 늦은 거 알아요.이게 도움이 됐으면 좋겠네요!

실행: 이 메서드를 호출하여 3개의 인수를 전달합니다.

  1. WebDriver 변수 // driver_variable을 드라이버로 가정합니다.
  2. 체크할 요소.By 메서드에서 제공해야 합니다.// ex: By.id paramid")
  3. 시간 제한(초).

예: wait For Element Present(드라이버, By.id privid", 10 );

public static WebElement waitForElementPresent(WebDriver driver, final By by, int timeOutInSeconds) {

        WebElement element; 

        try{
            driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //nullify implicitlyWait() 

            WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds); 
            element = wait.until(ExpectedConditions.presenceOfElementLocated(by));

            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //reset implicitlyWait
            return element; //return the element
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return null; 
    }

이것으로 충분합니다.

 if(!driver.findElements(By.xpath("//*[@id='submit']")).isEmpty()){
    //THEN CLICK ON THE SUBMIT BUTTON
}else{
    //DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE
}

try catch 스테이트먼트 전에 selenium 타임아웃을 짧게 함으로써 코드를 보다 빠르게 실행할 수 있습니다.

요소가 존재하는지 확인하기 위해 다음 코드를 사용합니다.

protected boolean isElementPresent(By selector) {
    selenium.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
    logger.debug("Is element present"+selector);
    boolean returnVal = true;
    try{
        selenium.findElement(selector);
    } catch (NoSuchElementException e){
        returnVal = false;
    } finally {
        selenium.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
    }
    return returnVal;
}

Java를 사용하여 다음 함수/방법을 작성합니다.

protected boolean isElementPresent(By by){
        try{
            driver.findElement(by);
            return true;
        }
        catch(NoSuchElementException e){
            return false;
        }
    }

어설션 중에 적절한 파라미터를 사용하여 메서드를 호출합니다.

루비에서 rspec-Webdriver를 사용하는 경우 요소가 존재하지 않고 테스트에 합격했다고 가정하여 이 스크립트를 사용할 수 있습니다.

먼저, 당신의 클래스 RB 파일에서 이 방법을 쓰세요.

class Test
 def element_present?
    begin
        browser.find_element(:name, "this_element_id".displayed?
        rescue Selenium::WebDriver::Error::NoSuchElementError
            puts "this element should not be present"
        end
 end

그런 다음 스펙 파일에서 해당 메서드를 호출합니다.

  before(:all) do    
    @Test= Test.new(@browser)
  end

 @Test.element_present?.should == nil

요소가 존재하지 않으면 사양에 합격하지만 요소가 있으면 오류가 발생하며 테스트에 실패했습니다.

public boolean isElementDisplayed() {
        return !driver.findElements(By.xpath("...")).isEmpty();
    }

개인적으로는 항상 위의 답변들을 혼합하여 재사용 가능한 스태틱 유틸리티 메서드를 만듭니다.size() > 0제안:

public Class Utility {
   ...
   public static boolean isElementExist(WebDriver driver, By by) {
      return driver.findElements(by).size() > 0;
   ...
}

깔끔하고, 재사용 가능하며, 유지보수가 가능합니다.다양한 물건입니다.-)

특정 요소가 존재하는지 여부를 확인하려면 findElement() 대신 findElement() 메서드를 사용해야 합니다.

int i=driver.findElements(By.xpath(".......")).size();
if(i=0)
System.out.println("Element is not present");
else
System.out.println("Element is present");

이건 나한테 효과가 있어내가 틀렸다면 제안해줘..

이것으로 충분합니다.

try {
    driver.findElement(By.id(id));
} catch (NoSuchElementException e) {
    //do what you need here if you were expecting
    //the element wouldn't exist
}

내 코드 조각을 주고 있어따라서, 아래 방법은 페이지에 임의의 웹 요소 'Create New Application' 버튼이 존재하는지 여부를 확인합니다.대기시간은 0초로 사용하고 있습니다.

public boolean isCreateNewApplicationButtonVisible(){
    WebDriverWait zeroWait = new WebDriverWait(driver, 0);
    ExpectedCondition<WebElement> c = ExpectedConditions.presenceOfElementLocated(By.xpath("//input[@value='Create New Application']"));
    try {
        zeroWait.until(c);
        logger.debug("Create New Application button is visible");
        return true;
    } catch (TimeoutException e) {
        logger.debug("Create New Application button is not visible");
        return false;
    }
}

다음과 같은 것을 사용하고 싶습니다(Scala의 경우(구 「좋은」Java 8의 코드는 이것과 비슷할 수 있습니다.

object SeleniumFacade {

  def getElement(bySelector: By, maybeParent: Option[WebElement] = None, withIndex: Int = 0)(implicit driver: RemoteWebDriver): Option[WebElement] = {
    val elements = maybeParent match {
      case Some(parent) => parent.findElements(bySelector).asScala
      case None => driver.findElements(bySelector).asScala
    }
    if (elements.nonEmpty) {
      Try { Some(elements(withIndex)) } getOrElse None
    } else None
  }
  ...
}

그러면

val maybeHeaderLink = SeleniumFacade getElement(By.xpath(".//a"), Some(someParentElement))

Java에서 찾은 가장 간단한 방법은 다음과 같습니다.

List<WebElement> linkSearch=  driver.findElements(By.id("linkTag"));
int checkLink=linkSearch.size();
if(checkLink!=0){  //do something you want}

암묵적인 대기를 시도할 수 있습니다.

WebDriver driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
driver.Url = "http://somedomain/url_that_delays_loading";
IWebElement myDynamicElement = driver.FindElement(By.Id("someDynamicElement"));

또는 명시적 대기 상태를 시도할 수 있습니다.

IWebDriver driver = new FirefoxDriver();
driver.Url = "http://somedomain/url_that_delays_loading";
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
    {
        return d.FindElement(By.Id("someDynamicElement"));
    });

명시적(Explicit)은 일부 작업 전에 요소가 존재하는지 확인합니다.암묵적인 대기는 코드의 모든 장소에서 호출할 수 있습니다.예를 들어 일부 AJAX 작업 후.

Selenium에서 더 많은 정보를 찾을 수 있습니다.HQ 페이지

2022년에는 번거로운 지연이나 현재 암묵적인 대기 값에 영향을 주지 않고 이 작업을 수행할 수 있게 되었습니다.

최신 버전(현재의 「현재의」)으로.4.1.2)을 사용하면, 「」를 사용할 수 .getImplicitWaitTimeout그런 다음 대기 시간을 피하기 위해 타임아웃을 0으로 설정하고 이전의 암묵적인 대기 값을 복원합니다.



    Duration implicitWait = driver.manage().timeouts().getImplicitWaitTimeout();
    driver.manage().timeouts().implicitlyWait(Duration.ofMillis(0));
    final List signOut = driver.findElements(By.linkText("Sign Out"));
    driver.manage().timeouts().implicitlyWait(implicitWait); // Restore implicit wait to previous value
    
    if (!signOut.isEmpty()) {
        ....
    }

isDisplayed() 메서드를 사용하여 아래 코드를 사용하여 요소의 존재 여부를 확인할 수 있습니까?

WebElement element=driver.findElements(By.xpath(""));
element.isDispplayed();

언급URL : https://stackoverflow.com/questions/7991522/test-if-element-is-present-using-selenium-webdriver

반응형