Selenium WebDriver를 사용하여 요소가 존재하는지 테스트합니까?
요소가 있는지 테스트하는 방법이 있습니까? findElement 메소드는 예외로 끝날 것입니다.하지만 요소가 존재하지 않고 테스트에 실패하지 않아서 예외가 해결책이 될 수 없기 때문에 원하는 것은 아닙니다.
나는이 게시물을 발견했다 : Selenium c # Webdriver : 요소가 나타날 때까지 기다리십시오. 그러나 이것은 C #을위한 것이며 아주 잘하지 않습니다. 누구나 코드를 Java로 번역 할 수 있습니까? 죄송합니다. Eclipse에서 사용해 보았지만 Java 코드로 올바르게 가져 가지 못했습니다.
이것은 코드입니다.
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);
}
}
findElements
대신에 사용하십시오 findElement
.
findElements
예외 대신 일치하는 요소가 없으면 빈 목록을 반환합니다.
요소가 존재하는지 확인하려면 다음을 시도하십시오.
Boolean isPresent = driver.findElements(By.yourLocator).size() > 0
하나 이상의 요소가 발견되면 true를 리턴하고 존재하지 않으면 false를 리턴합니다.
단순히 요소를 찾고 다음과 같이 존재하는지 판별하는 개인용 메소드는 어떻습니까?
private boolean existsElement(String id) {
try {
driver.findElement(By.id(id));
} catch (NoSuchElementException e) {
return false;
}
return true;
}
이것은 매우 쉽고 일을합니다.
편집 : 더 나아가서 By elementLocator
매개 변수로 as를 사용할 수 있으므로 id 이외의 요소로 요소를 찾으려면 문제를 제거하십시오.
나는 이것이 자바에서 작동한다는 것을 발견했다.
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 문을 실행하여 찾을 수 없음을 알려줍니다.
이것은 안에 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
알려주고 계속 진행했습니다. 문제의 요소가 존재하면 필요한 테스트를 실행할 수 없습니다.이를 설정 해야하는 주된 이유입니다.
요소가 존재하지 않고 페이지에 표시되지 않는 경우 if else에 테스트를 실행하는 else가 있습니다.
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에 대한 응답이 약간 늦었다는 것을 알고 있습니다. 잘만되면 이것은 누군가를 돕는다!
이것을보십시오 :이 방법을 호출하고 세 가지 인수를 전달하십시오 :
- WebDriver 변수. // driver_variable을 driver로 가정합니다.
- 확인할 요소입니다. By 메소드에서 제공해야합니다. // 예 : By.id ( "id")
- 시간 제한 (초)
예 : waitForElementPresent (driver, By.id ( "id"), 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;
}
try catch 문 전에 셀레늄 시간 초과를 줄이면 코드를 더 빠르게 실행할 수 있습니다.
I use the following code to check if an element is present.
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;
}
Write the following function/methos using Java:
protected boolean isElementPresent(By by){
try{
driver.findElement(by);
return true;
}
catch(NoSuchElementException e){
return false;
}
}
Call the method with appropriate parameter during assertion.
if you are using rspec-Webdriver in ruby, you can use this script assuming that an element should really not be present and it is a passed test.
First, write this method first from your class RB file
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
Then, on your spec file, call that method.
before(:all) do
@Test= Test.new(@browser)
end
@Test.element_present?.should == nil
If your the element is NOT present, your spec will pass, but if the element is present , it will throw an error, test failed.
This works for me:
if(!driver.findElements(By.xpath("//*[@id='submit']")).isEmpty()){
//THEN CLICK ON THE SUBMIT BUTTON
}else{
//DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE
}
To find a particular Element is present or not, we have to use findElements() method instead of 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");
this is worked for me.. suggest me if i am wrong..
This should do it:
try {
driver.findElement(By.id(id));
} catch (NoSuchElementException e) {
//do what you need here if you were expecting
//the element wouldn't exist
}
Giving my snippet of code. So, the below method checks if a random web element 'Create New Application' button exists on a page or not. Note that I have used the wait period as 0 seconds.
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;
}
}
I would use something like (with Scala [the code in old "good" Java 8 may be similar to this]):
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
}
...
}
so then,
val maybeHeaderLink = SeleniumFacade getElement(By.xpath(".//a"), Some(someParentElement))
public boolean isElementDisplayed() {
return !driver.findElements(By.xpath("...")).isEmpty();
}
Simplest way I found in Java is:
List<WebElement> linkSearch= driver.findElements(By.id("linkTag"));
int checkLink=linkSearch.size();
if(checkLink!=0){ //do something you want}
You can try implicit wait:
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"));
`
Or You can try explicit wait one: `
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 will check if element is present before some action. Implicit wait could be call in every place in the code. For example after some AJAX actions.
More you can find at SeleniumHQ page
Personally, I always go for a mixture of the above answers and create a re-usable static Utility method that uses the size()<0 suggestion:
public Class Utility {
...
public static boolean isElementExist(WebDriver driver, By by) {
return driver.findElements(by).size() < 0;
...
}
This is neat, re-usable, maintainable ... all that good stuff ;-)
참고URL : https://stackoverflow.com/questions/7991522/test-if-element-is-present-using-selenium-webdriver
'IT' 카테고리의 다른 글
서브 플롯에 대한 pyplot 좌표축 레이블 (0) | 2020.06.12 |
---|---|
python의 eval () 대 ast.literal_eval ()을 사용합니까? (0) | 2020.06.12 |
Mathematica 도구 가방에 무엇입니까? (1) | 2020.06.12 |
Go 구조체를 JSON으로 변환 (0) | 2020.06.12 |
파이썬에서 객체의 유형을 비교하는 방법은 무엇입니까? (0) | 2020.06.12 |