버튼을 클릭하면 열리는 새 브라우저 창으로 전환하는 방법
버튼을 클릭하면 검색 결과가 나오는 새로운 브라우저 창이 열리는 상황이 있습니다.
새로 열린 브라우저 창에 연결하여 포커스를 맞추는 방법이 있습니까?
그리고 작업을 한 후 원래 창으로 돌아갑니다.
다음과 같이 창을 전환할 수 있습니다.
// Store the current window handle
String winHandleBefore = driver.getWindowHandle();
// Perform the click operation that opens new window
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
// Perform the actions on new window
// Close the new window, if that window no more required
driver.close();
// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
// Continue with original browser (first window)
내용에 덧붙이자면...
메인 창(기본 창)으로 돌아가려면
사용하다driver.switchTo().defaultContent();
이 스크립트는 [Parent]창에서 [Child]창으로 전환하여 cntrl을 [Parent]창으로 되돌리는 데 도움이 됩니다
String parentWindow = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for(String windowHandle : handles)
{
if(!windowHandle.equals(parentWindow))
{
driver.switchTo().window(windowHandle);
<!--Perform your operation here for new window-->
driver.close(); //closing child window
driver.switchTo().window(parentWindow); //cntrl to parent window
}
}
반복기와 while loop을 사용하여 다양한 윈도우 핸들을 저장한 후 앞뒤로 전환합니다.
//Click your link
driver.findElement(By.xpath("xpath")).click();
//Get all the window handles in a set
Set <String> handles =driver.getWindowHandles();
Iterator<String> it = handles.iterator();
//iterate through your windows
while (it.hasNext()){
String parent = it.next();
String newwin = it.next();
driver.switchTo().window(newwin);
//perform actions on new window
driver.close();
driver.switchTo().window(parent);
}
수리아, 네 방식이 먹히지 않을 거야 두 가지 이유 때문이지
- 테스트 평가 중에는 드라이버의 포커스가 흐트러지기 때문에 액티브 요소로 전환하기 전에 드라이버를 닫을 수 없으며 NoSch Window Exception이 표시됩니다.
- ChromeDriver에서 테스트를 실행하면 창이 뜨지 않고 어플리케이션에서 클릭해서 탭이 나타납니다.Selenium Driver는 탭으로 동작할 수 없기 때문에 창 사이를 전환할 뿐이며, 새로운 탭이 열리는 곳을 클릭할 때 정지하고 타임아웃 시 크래시합니다.
IE의 레지스트리 수정:
- HKEY_CURRENT_USER\소프트웨어\Microsoft\Internet Explorer\메인
- → 새로 만들기 → 문자열 값 → 값 이름을 마우스 오른쪽 버튼으로 클릭합니다.TabProcGrowth(존재하지 않는 경우 작성)
- TabProcGrowth(우클릭) → 수정...→ 값 데이터 : 0
출처: Internet Explorer 8-10의 Selenium WebDriver 윈도 스위칭 문제
제 경우 레지스트리를 편집한 후 IE가 새로운 창 핸들을 검출하기 시작했습니다.
MSDN 블로그에서 가져온 내용:
Tab Process Growth : IE가 New Tab 프로세스를 작성하는 속도를 설정합니다.
"Max-Number" 알고리즘:특정 Mandatory Integrity Level(MIC; 필수 무결성 수준)에서 단일 프레임프로세스에 대해 단일 분리 세션에서 실행할 수 있는 탭프로세스의 최대 수를 지정합니다.상대값은 다음과 같습니다.
- TabProcGrowth=0 : 탭과 프레임은 동일한 프로세스 내에서 실행되며 프레임은 MIC 레벨에서 통합되지 않습니다.
- TabProcGrowth = 1: 특정 프레임 프로세스의 모든 탭은 특정 MIC 레벨의 단일 탭 프로세스로 실행됩니다.
인터넷 옵션:
- 보안 → 모든 영역(인터넷, 로컬 인트라넷, 신뢰할 수 있는 사이트, 제한된 사이트)에 대해 보호 모드 활성화하기
- Advanced → Security → Enhanced Protected Mode 활성화하기
코드:
브라우저: IE11 x 64 (줌: 100%)
OS: Windows 7 x 64
셀렌: 3.5.1
Web Driver: IEDriver Server x 64 3.5.1
public static String openWindow(WebDriver driver, By by) throws IOException {
String parentHandle = driver.getWindowHandle(); // Save parent window
WebElement clickableElement = driver.findElement(by);
clickableElement.click(); // Open child window
WebDriverWait wait = new WebDriverWait(driver, 10); // Timeout in 10s
boolean isChildWindowOpen = wait.until(ExpectedConditions.numberOfWindowsToBe(2));
if (isChildWindowOpen) {
Set<String> handles = driver.getWindowHandles();
// Switch to child window
for (String handle : handles) {
driver.switchTo().window(handle);
if (!parentHandle.equals(handle)) {
break;
}
}
driver.manage().window().maximize();
}
return parentHandle; // Returns parent window if need to switch back
}
/* How to use method */
String parentHandle = Selenium.openWindow(driver, by);
// Do things in child window
driver.close();
// Return to parent window
driver.switchTo().window(parentHandle);
위의 코드에는 Java에서 순서가 보장되지 않으므로 부모 창으로 전환하지 않는지 확인하는 if-check가 포함되어 있습니다. WebDriverWait
는, 이하의 스테이트먼트에 의해서 서포트되고 있는 것처럼, 성공 가능성이 높아집니다.
Luke Inman-Semerau에서 인용: (Selenium 개발자)
브라우저가 새 창을 확인하는 데 시간이 걸릴 수 있으며 팝업창이 뜨기 전에 switchTo() 루프에 빠질 수 있습니다.
자동으로 getWindowHandles()에 의해 마지막으로 열린 창이 될 것으로 가정합니다.반드시 그렇지는 않습니다. 어떤 순서로든 반품할 수 있는 것은 아니기 때문입니다.
관련 투고:
다음을 사용할 수 있습니다.
driver.SwitchTo().Window(WindowName);
여기서 WindowName은 포커스를 전환하는 창의 이름을 나타내는 문자열입니다.작업이 끝나면 원래 창의 이름으로 이 함수를 다시 호출하여 원래 창으로 돌아갑니다.
main you can do :
String mainTab = page.goToNewTab ();
//do what you want
page.backToMainPage(mainTab);
What you need to have in order to use the main
private static Set<String> windows;
//get all open windows
//return current window
public String initWindows() {
windows = new HashSet<String>();
driver.getWindowHandles().stream().forEach(n -> windows.add(n));
return driver.getWindowHandle();
}
public String getNewWindow() {
List<String> newWindow = driver.getWindowHandles().stream().filter(n -> windows.contains(n) == false)
.collect(Collectors.toList());
logger.info(newWindow.get(0));
return newWindow.get(0);
}
public String goToNewTab() {
String startWindow = driver.initWindows();
driver.findElement(By.cssSelector("XX")).click();
String newWindow = driver.getNewWindow();
driver.switchTo().window(newWindow);
return startWindow;
}
public void backToMainPage(String startWindow) {
driver.close();
driver.switchTo().window(startWindow);
}
따라서 이러한 솔루션의 많은 문제는 창이 즉시 나타난다고 가정하는 것입니다(즉각적으로 아무 일도 일어나지 않고 IE에서는 훨씬 더 적은 시간이 소요됨).또한 요소를 클릭하기 전에 창이 하나밖에 없다고 가정하지만 항상 그렇지는 않습니다.또한 IE는 창 핸들을 예측 가능한 순서로 반환하지 않습니다.그래서 저는 다음과 같이 하겠습니다.
public String clickAndSwitchWindow(WebElement elementToClick, Duration
timeToWaitForWindowToAppear) {
Set<String> priorHandles = _driver.getWindowHandles();
elementToClick.click();
try {
new WebDriverWait(_driver,
timeToWaitForWindowToAppear.getSeconds()).until(
d -> {
Set<String> newHandles = d.getWindowHandles();
if (newHandles.size() > priorHandles.size()) {
for (String newHandle : newHandles) {
if (!priorHandles.contains(newHandle)) {
d.switchTo().window(newHandle);
return true;
}
}
return false;
} else {
return false;
}
});
} catch (Exception e) {
Logging.log_AndFail("Encountered error while switching to new window after clicking element " + elementToClick.toString()
+ " seeing error: \n" + e.getMessage());
}
return _driver.getWindowHandle();
}
이 기능은 Selenium 4 이후 버전에서 작동합니다.
// Opens a new tab and switches to new tab
driver.switchTo().newWindow(WindowType.TAB);
// Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW);
브라우저가 여러 개 있는 경우(Java 8 사용)
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestLink {
private static Set<String> windows;
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/Users/radler/Desktop/myLink.html");
setWindows(driver);
driver.findElement(By.xpath("//body/a")).click();
// get new window
String newWindow = getWindow(driver);
driver.switchTo().window(newWindow);
// Perform the actions on new window
String text = driver.findElement(By.cssSelector(".active")).getText();
System.out.println(text);
driver.close();
// Switch back
driver.switchTo().window(windows.iterator().next());
driver.findElement(By.xpath("//body/a")).click();
}
private static void setWindows(WebDriver driver) {
windows = new HashSet<String>();
driver.getWindowHandles().stream().forEach(n -> windows.add(n));
}
private static String getWindow(WebDriver driver) {
List<String> newWindow = driver.getWindowHandles().stream()
.filter(n -> windows.contains(n) == false).collect(Collectors.toList());
System.out.println(newWindow.get(0));
return newWindow.get(0);
}
}
언급URL : https://stackoverflow.com/questions/9588827/how-to-switch-to-the-new-browser-window-which-opens-after-click-on-the-button
'programing' 카테고리의 다른 글
마리아DB 10센트OS 7 데이터 이동 문제 (0) | 2023.01.27 |
---|---|
CollapsingToolbarLayout이 스크롤 플링을 인식하지 않습니다. (0) | 2023.01.27 |
Importorr: libmariadbclient.so18: 공유 개체 파일을 열 수 없습니다.해당 파일 또는 디렉터리가 없습니다. (0) | 2023.01.27 |
이름이 없는 로더 'app' 모듈에 있으므로 클래스에 캐스팅할 수 없습니다. (0) | 2023.01.27 |
JSON 구문 분석 중 "예기치 않은 토큰 o" 오류가 발생했습니다. (0) | 2023.01.27 |