2015-01-25 3 views
1

각 페이지의 요소를 확인하고 현재 페이지에 표시되어 있으면 일부 어설 션을하고 싶습니다. 내 코드는 다음과 같습니다webdriver org.openqa.selenium.NoSuchElementException : 요소를 찾을 수 없습니다.

package com.example.tests; 

import java.util.Iterator; 
import java.util.List; 
import java.util.regex.Pattern; 
import java.util.concurrent.TimeUnit; 

import org.junit.*; 

import static org.junit.Assert.*; 
import static org.hamcrest.CoreMatchers.*; 

import org.openqa.selenium.*; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.openqa.selenium.support.ui.Select; 

import com.thoughtworks.selenium.Selenium; 
import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium; 

public class Webdriver_class { 
    private WebDriver driver; 
    private String baseUrl; 
    private boolean acceptNextAlert = true; 
    private StringBuffer verificationErrors = new StringBuffer(); 

    @Before 
    public void setUp() throws Exception { 
    driver = new FirefoxDriver(); 
    baseUrl = "http://www.lotto.pl/"; 
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
    } 

    @Test 
    public void testUntitled() throws Exception { 
    driver.get(baseUrl + "/lotto/wyniki-i-wygrane/wygrane"); 
    assertEquals("Wyniki i wygrane Lotto i Lotto Plus | Lotto, Kaskada, Multi Multi, Mini Lotto, Joker, Zdrapki - lotto.pl", driver.getTitle()); 
    assertEquals("28-07-11", driver.findElement(By.xpath("//div[@id='page']/div[3]/div[2]/div[2]/table/tbody/tr[77]/td[5]")).getText()); 

    ///number of pages/// 
    String xpath = "html/body/div[3]/div[1]/div/div[3]/div[2]/div[2]/div[3]/div/ul/li"; 
    List<WebElement> elements = driver.findElements(By.xpath(xpath)); 
    int x=elements.size(); 
    System.out.println("liczba stron = "+elements.size()); 

    ////end////// 


    for(int i=1; i<=x; i++){ 


      if(driver.findElement(By.xpath("//div[@id='page']/div[3]/div[2]/div[2]/table/tbody/tr[contains(td[3],'Warszawa') and contains (td[5],'21-02-09')]/td[1]")) != null) 

       { assertEquals("100.", driver.findElement(By.xpath("//div[@id='page']/div[3]/div[2]/div[2]/table/tbody/tr[contains(td[3],'Warszawa') and contains (td[5],'21-02-09')]/td[1]")).getText()); 
       assertEquals("100.", driver.findElement(By.xpath("//div[@id='page']/div[3]/div[2]/div[2]/table/tbody/tr[contains(td[3],'Warszawa') and contains (td[5],'21-02-09')]/td[1]")).getText()); 
      }; 

      if(driver.findElement(By.xpath("//div[@id='page']/div[3]/div[2]/div[2]/table/tbody/tr[contains(td[3],'Nowa Sól') and contains (td[5],'05-04-12')]/td[1]")) != null) 
      { assertEquals("99.", driver.findElement(By.xpath("//div[@id='page']/div[3]/div[2]/div[2]/table/tbody/tr[contains(td[3],'Nowa Sól') and contains (td[5],'05-04-12')]/td[1]")).getText()); 
      }; 


      //go to the new page// 

      driver.findElement(By.xpath("html/body/div[3]/div[1]/div/div[3]/div[2]/div[2]/div[3]/div/ul/li/a["+i+"]")).click(); 
         for (int second = 0;; second++) { 
       if (second >= 60) fail("timeout- nie znalazł 'Wyniki i wygrane Lotto i Lotto Plus' "); 
       try { if ("Wyniki i wygrane Lotto i Lotto Plus".equals(driver.findElement(By.cssSelector("h1.title")).getText())) break; } catch (Exception e) {} 
       Thread.sleep(50000); 
      } 

    } 

    } 
} 

첫 페이지 괜찮 있지만 두 번째 페이지로 이동 때 오류 얻을에, 그래서 모든 요소는 첫 번째 페이지에서 볼 수 있습니다 :

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//div[@id='page']/div[3]/div[2]/div[2]/table/tbody/tr[contains(td[3],'Warszawa') and contains (td[5],'21-02-09')]/td[1]"} 
Command duration or timeout: 30.10 seconds 
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html 

수있는 사람의 도움을 그것으로. IF 문을 사용할 때 왜이 오류가 발생합니까? 'Webdriver'does not는 element = doesnt가 ​​어설 션을 찾지 못하도록합니까? 이 요소를 찾을 수 나던 때 는 그럼 가야 더

, 그것은 :)

감사

+1

두 번째 페이지에 요소가 없기 때문에 요소를 볼 수 있는지 확인하십시오. 보이지 않는 경우 해당 요소가 표시되는지 확인한 다음 해당 요소를 클릭하지 마십시오. – Innovation

+0

첫 페이지와 두 번째 페이지 HTML 스 니펫을 게시하는 데 도움을주십시오. –

답변

1

을이 오류의 원인이 될 수 있습니다 작업을 만들기 위해 무엇을 도와주세요 요소가 당신 xpath로 찾으려고합니다. -

//div[@id='page']/div[3]/div[2]/div[2]/table/tbody/tr[contains(td[3],'Warszawa') and contains (td[5],'21-02-09')]/td[1] 

이 두 번째 페이지에 없습니다. 따라서 요소가 있는지 여부를 확인하기 위해 if을 사용한 경우에도 webdriver가 요소를 찾을 수없는 경우 셀렌은 NoSuchElementException 예외를 throw합니다. 그것은 간단하게하기 위해, 이런 식으로 넣어 보자 : -

if (driver.findElement(By.xpath(element_xpath)) != null) 
{ 
    do_some_stuff 
} 

이제 다음과 같이 현실을 깰 수 있도록 : -

is_present = driver.findElement(By.xpath(element_xpath)) 
if(is_present != null) 
{ 
    do_some_stuff 
} 

위의 코드 조각은 단순화 된 이전의 버전이있다 프로그램을 실행하는 동안 이전 코드가 평가되는 방법입니다. 즉, 먼저 if 블록 내부의 조건이 평가됩니다 (귀하의 경우 driver.findElement(By.xpath())). 그 결과는 null과 비교됩니다. 첫 번째 경우 webdriver는 지정된 xpath를 사용하여 요소를 찾으려고하지만 찾을 수 없습니다. .. 예외가 발생되면 그래서 NoSuchElementException 예외가 발생 webdriver 그 시점 자체에 따라서, 파이썬은 더 이상 그것을 평가하지 않고 프로그램이 종료

그것을 해결하기 위해, try-catch 블록 안에 넣어 : -.

try 
    { 
    if (driver.findElement(By.xpath(element_xpath)) != null) 
     { 
     do_some_stuff 
     } 
    } 
catch(Exception e) 
    { 
    System.out.println(e); 
    System.out.println("Element not found"); 
    } 

따라서 webdriver가 종료 대신 주어진 요소를 찾지 못하는 예외를 발견하더라도 프로그램을 시작하면 코드가 계속 이동하고 다음 코드 부분이 실행됩니다. catch 블록이 exception을 처리하고 프로그램이 더 나아갈 수 있기 때문입니다. 이 exception을의에 의해

나는 다음 if 블록이 영향을받지 않습니다 당신의 if 블록의이 exception있는 경우에도, 당신은 try-catch 내의 각 if 블록을 넣어하는 것이 좋습니다, 그래서 것이다.

희망 사항을 입력하면 문제가 해결됩니다.

관련 문제