WebDriver로 요소가 표시되는지 확인하는 방법
함께 WebDriver
요소가 표시되는 경우 셀레늄 2.0a2에서 나는 문제 검사를 데.
WebDriver.findElement
WebElement
불행히도 isVisible
메서드를 제공하지 않는를 반환합니다 . 를 사용 WebElement.clear
하거나 WebElement.click
둘 다 사용하여이 문제를 해결할 수 ElementNotVisibleException
있지만 이것은 매우 더럽습니다.
더 좋은 아이디어가 있습니까?
element instanceof RenderedWebElement
작동해야합니다.
질문에 다소 늦었음에도 불구하고 :
이제를 사용 WebElement.isDisplayed()
하여 요소가 표시되는지 확인할 수 있습니다.
참고 :
요소가 보이지 않는 데에는 여러 가지 이유가 있습니다. Selenium 시도는 대부분을 커버하지만 예상대로 작동하지 않는 경우가 있습니다.
예를 들어, isDisplayed()
수행 수익을 false
요소가있는 경우 display: none
나 opacity: 0
,하지만 요소는 CSS 위치에 다른 인해이 적용되는 경우 내 테스트에서 적어도, 그것은 안정적으로 감지하지 않습니다.
다음 두 가지 제안 된 방법이 있습니다.
isDisplayed()
다음과 같이 사용할 수 있습니다 .driver.findElement(By.id("idOfElement")).isDisplayed();
아래와 같이 메소드를 정의하고 호출 할 수 있습니다.
public boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (org.openqa.selenium.NoSuchElementException e) { return false; } }
이제 다음과 같이 어설 션을 수행하여 요소가 있는지 여부를 확인할 수 있습니다.
assertTrue(isElementPresent(By.id("idOfElement")));
C #을 사용하는 경우 driver.Displayed입니다. 다음은 내 프로젝트의 예입니다.
if (!driver.FindElement(By.Name("newtagfield")).Displayed) //if the tag options is not displayed
driver.FindElement(By.Id("expand-folder-tags")).Click(); //make sure the folder and tags options are visible
짧은 대답 : 사용 #visibilityOfElementLocated
사용 isDisplayed
하거나 유사한 답변 이 정확하지 않습니다. display
속성이 아닌지 여부 만 확인 none
하고 요소를 실제로 볼 수 있는지 확인 하지 않습니다! Selenium에는 ExpectedConditions
클래스 에 많은 정적 유틸리티 메소드가 추가되었습니다 . 이 경우 두 가지를 사용할 수 있습니다.
- visibleOfElementLocated (요소가 존재하지 않도록 허용됨)
- visibleOf (요소가 있어야 함)
용법
@Test
// visibilityOfElementLocated has been statically imported
public demo(){
By searchButtonSelector = By.className("search_button");
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.get(homeUrl);
WebElement searchButton = wait.until(
visibilityOfElementLocated
(searchButtonSelector));
//clicks the search button
searchButton.click();
클라이언트에서 실행되는 사용자 지정 가시성 검사
에서 유틸리티 방법에 대해 알아보기 전에 이것은 내 대답이었습니다 ExpectedConditions
. 위에서 언급 한 방법보다 더 많은 작업을 수행한다고 가정하므로 여전히 관련성이있을 수 있습니다. 요소에 높이와 너비 만 있는지 확인합니다.
본질적으로이 자바와 응답 할 수없는 findElementBy*
방법과 WebElement#isDisplayed
요소가 있다면 그들은 단지 당신을 말할 수있는, 혼자 존재 가 실제로하지 않으면 볼 . OP는 보이는 의미를 정의하지 않았지만 일반적으로
- 그것은 갖는다
opacity
> 0 - 그것은이
display
보다 뭔가 다른 속성 집합을none
visibility
소품이 설정되어visible
- 그것을 숨기는 다른 요소가 없습니다 (최상위 요소입니다)
대부분의 사람들은 또한 실제로 뷰포트 내에 있어야한다는 요구 사항을 포함합니다 (따라서 사람이 볼 수 있음).
어떤 이유에서인지이 아주 정상적인 요구는 순수한 Java API로 충족되지 않는 반면,이를 기반으로하는 Selenium의 프론트 엔드는 종종.의 일부 변형을 구현하므로 isVisible
이것이 가능해야한다는 것을 알았습니다. 그리고 노드 프레임 워크의 소스를 탐색 한 후 WebDriver.IO 내가 찾은 소스 의 isVisible
현재의 더 적절 이름으로 이름이 변경되고, isVisibleInViewport
5.0 베타에 있습니다.
기본적으로 클라이언트에서 실행되고 실제 작업을 수행 하는 javascript에 위임 하는 호출로 사용자 지정 명령을 구현합니다 ! 이것은 "서버"비트입니다.
export default function isDisplayedInViewport () {
return getBrowserObject(this).execute(isDisplayedInViewportScript, {
[ELEMENT_KEY]: this.elementId, // w3c compatible
ELEMENT: this.elementId // jsonwp compatible
})
}
따라서 흥미로운 부분은 클라이언트에서 실행되도록 전송 된 자바 스크립트입니다.
/**
* check if element is visible and within the viewport
* @param {HTMLElement} elem element to check
* @return {Boolean} true if element is within viewport
*/
export default function isDisplayedInViewport (elem) {
const dde = document.documentElement
let isWithinViewport = true
while (elem.parentNode && elem.parentNode.getBoundingClientRect) {
const elemDimension = elem.getBoundingClientRect()
const elemComputedStyle = window.getComputedStyle(elem)
const viewportDimension = {
width: dde.clientWidth,
height: dde.clientHeight
}
isWithinViewport = isWithinViewport &&
(elemComputedStyle.display !== 'none' &&
elemComputedStyle.visibility === 'visible' &&
parseFloat(elemComputedStyle.opacity, 10) > 0 &&
elemDimension.bottom > 0 &&
elemDimension.right > 0 &&
elemDimension.top < viewportDimension.height &&
elemDimension.left < viewportDimension.width)
elem = elem.parentNode
}
return isWithinViewport
}
JS의이 조각은 실제로 그대로 자신의 코드베이스에 (거의) 복사 (제거 할 수 있습니다 export default
및 교체 const
와 var
비 상록 브라우저의 경우)! 그것을 사용하려면에서 읽을 File
로 String
클라이언트에서 실행하는 셀레늄에 의해 전송 될 수있다.
살펴볼 가치가있는 또 다른 흥미롭고 관련 스크립트는 selectByVisibleText 입니다.
Selenium을 사용하여 JS를 실행하지 않았다면 이것에 대해 살짝 엿보 거나 JavaScriptExecutor API를 찾아 볼 수 있습니다 .
일반적으로 항상 비 차단 비동기 스크립트 ( #executeAsyncScript를 의미 )를 사용하려고 하지만 이미 동기식 차단 스크립트가 있으므로 일반 동기화 호출을 사용하는 것이 좋습니다. 반환 된 객체는 여러 유형의 객체가 될 수 있으므로 적절하게 캐스팅하십시오. 이것은 한 가지 방법이 될 수 있습니다.
/**
* Demo of a java version of webdriverio's isDisplayedInViewport
* https://github.com/webdriverio/webdriverio/blob/v5.0.0-beta.2/packages/webdriverio/src/commands/element/isDisplayedInViewport.js
* The super class GuiTest just deals with setup of the driver and such
*/
class VisibleDemoTest extends GuiTest {
public static String readScript(String name) {
try {
File f = new File("selenium-scripts/" + name + ".js");
BufferedReader reader = new BufferedReader( new FileReader( file ) );
return reader.lines().collect(Collectors.joining(System.lineSeparator()));
} catch(IOError e){
throw new RuntimeError("No such Selenium script: " + f.getAbsolutePath());
}
}
public static Boolean isVisibleInViewport(RemoteElement e){
// according to the Webdriver spec a string that identifies an element
// should be deserialized into the corresponding web element,
// meaning the 'isDisplayedInViewport' function should receive the element,
// not just the string we passed to it originally - how this is done is not our concern
//
// This is probably when ELEMENT and ELEMENT_KEY refers to in the wd.io implementation
//
// Ref https://w3c.github.io/webdriver/#dfn-json-deserialize
return js.executeScript(readScript("isDisplayedInViewport"), e.getId());
}
public static Boolean isVisibleInViewport(String xPath){
driver().findElementByXPath("//button[@id='should_be_visible']");
}
@Test
public demo_isVisibleInViewport(){
// you can build all kinds of abstractions on top of the base method
// to make it more Selenium-ish using retries with timeouts, etc
assertTrue(isVisibleInViewport("//button[@id='should_be_visible']"));
assertFalse(isVisibleInViewport("//button[@id='should_be_hidden']"));
}
}
Driver.FindElement
HTML 소스 만 확인하므로 요소가 표시되는지 여부를 확인하는 것이 중요합니다 . 그러나 팝업 코드는 페이지 html에있을 수 있으며 표시되지 않을 수 있습니다. 따라서 Driver.FindElement
함수는 거짓 긍정을 반환합니다 (테스트가 실패 함).
요소가 보이는지 확인합니다.
public static boolean isElementVisible(final By by)
throws InterruptedException {
boolean value = false;
if (driver.findElements(by).size() > 0) {
value = true;
}
return value;
}
Here is how I would do it (please ignore worry Logger class calls):
public boolean isElementExist(By by) {
int count = driver.findElements(by).size();
if (count>=1) {
Logger.LogMessage("isElementExist: " + by + " | Count: " + count, Priority.Medium);
return true;
}
else {
Logger.LogMessage("isElementExist: " + by + " | Could not find element", Priority.High);
return false;
}
}
public boolean isElementNotExist(By by) {
int count = driver.findElements(by).size();
if (count==0) {
Logger.LogMessage("ElementDoesNotExist: " + by, Priority.Medium);
return true;
}
else {
Logger.LogMessage("ElementDoesExist: " + by, Priority.High);
return false;
}
}
public boolean isElementVisible(By by) {
try {
if (driver.findElement(by).isDisplayed()) {
Logger.LogMessage("Element is Displayed: " + by, Priority.Medium);
return true;
}
}
catch(Exception e) {
Logger.LogMessage("Element is Not Displayed: " + by, Priority.High);
return false;
}
return false;
}
public boolean isElementFound( String text) {
try{
WebElement webElement = appiumDriver.findElement(By.xpath(text));
System.out.println("isElementFound : true :"+text + "true");
}catch(NoSuchElementException e){
System.out.println("isElementFound : false :"+text);
return false;
}
return true;
}
text is the xpath which you would be passing when calling the function.
the return value will be true if the element is present else false if element is not pressent
try{
if( driver.findElement(By.xpath("//div***")).isDisplayed()){
System.out.println("Element is Visible");
}
}
catch(NoSuchElementException e){
else{
System.out.println("Element is InVisible");
}
}
try this
public boolean isPrebuiltTestButtonVisible() {
try {
if (preBuiltTestButton.isEnabled()) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
참고URL : https://stackoverflow.com/questions/2646195/how-to-check-if-an-element-is-visible-with-webdriver
'developer tip' 카테고리의 다른 글
JavaScript에서 배열이 존재하는지 확인하는 방법은 무엇입니까? (0) | 2020.11.26 |
---|---|
Mercurial에서 hg 되돌리기 사용 (0) | 2020.11.26 |
PHP : array_map 함수에서 인덱스를 얻을 수 있습니까? (0) | 2020.11.26 |
PHP 스크립트에서 max_execution_time 가져 오기 (0) | 2020.11.26 |
사용자 정의 postgresql 열거 유형 정의를 표시하는 방법이 있습니까? (0) | 2020.11.26 |