Ayush Tiwari
Ayush Tiwari

Reputation: 131

How to get Handle of the Focused Tab in Selenium?

I am using Selenium for Scrapping purpose for Job Website scrapping. I am ctrl+clicking on jobs to go to second page and scrape details, I somehow wish to keep track of where I clicked to which tab opened up (using a map). But as soon as I ctrl+click an element, new tab opens and focus changes to that.

How do I get handle of the current focused tab in Selenium

I tried

webDriver.getWindowHandle()

But it returns me the handle for main tab that I ctrl+clicked an element from.

My Full Code

private void openAndMapJobTabs(WebElement jobList) {
        List<WebElement> jobRowsSelector = jobList.findElements(By.tagName("article"));
        for (WebElement jobRow : jobRowsSelector) {
            try {
                ctrlClickElement(jobRow);
                Thread.sleep(4000);
                //the next line is expected by me to give handle of current focused tab
                System.out.println(webDriver.getWindowHandle()); // but this gives me handle of main tab
                webElementToTabMapper.put(jobRow, webDriver.getWindowHandle());
                webDriver.switchTo().window(websiteTabHandle);
            } catch (Exception e) {
                logger.info("Could Not Click Open Job Tab: "+e.getMessage());
            }
        }
    }

UPDATE

Actually for me, I need to map elements to the tab they open, so order of tabs are important for me, so I purposely need the handle of current focused tab so I can map it with the element which opened that. But by iterating through all handels, I might mess up the order if any one of the webElement fails to open a new tab or if click is disabled on that.

Any help world be highly appreciated. Also if there are faster and better tools for scrapping, please recommend.

Upvotes: 1

Views: 174

Answers (1)

AbiSaran
AbiSaran

Reputation: 2678

You have to get the handles of those two tabs or windows, then you have to iterate and switch to the newly opened tab. Try the below code:

//      This line will get the handles of the all the tabs or windows and store in a var with type 'Set'
        Set<String> windowHandles = driver.getWindowHandles();
        
//      Iterating through the Set - i.e., window handles and switch to the other tab 
        for (String handle : windowHandles) {
//          System.out.println(handle);
            driver.switchTo().window(handle);
            System.out.println("Title: " + driver.getTitle());
        }

If you have more than two tabs or windows, then put the above code the in a method, pass the window title which you want to switch as a parameter, and compare the title with each window title, once you switch to the expected window, break.

Upvotes: 1

Related Questions