Selenium: How to get current url of a tab without switching to it?

1.9k Views Asked by At

I often open hundreds of tabs when using web browsers, and this slows my computer. So I want to write a browser manager in Python and Selenium , which opens tabs and can save the urls of those tabs, then I can reopen them later.

But it seems like the only way to get the url of a tab in Python Selenium is calling get_current_url.

I'm wondering if there's a way to get the url of a tab without switching to it?

4

There are 4 best solutions below

0
On BEST ANSWER

There is no other way to get the specific tab titles of the browser without switching to the specific TAB as Selenium needs focus on the DOM Tree to perform any operation.

3
On

Just go to the text link which is switching to other tab and save its @href attribute link into a string or list

0
On

I am not sure about your actual scenario but we can get the list of all hyperlinks present in the current page. The idea is to collect all web elements with tag "a" and later get their "href" attribute value. Below is a sample code in Java. Kindly modify it accordingly.

//Collecting all hyperlink elements
List<WebElement> allLinks = driver.findElements(By.tagName("a"));

//For each Hyperlink element getting its target href value 
for(WebElement link: allLinks)
{
    System.out.println(link.getAttribute("href"));
}

Hope this helps you. Thanks.

0
On

My recommendation is to use an extension for that or write/extend your own.
There seem to be some of those types like
https://addons.mozilla.org/en-US/firefox/addon/export-tabs-urls-and-titles/ or
https://chrome.google.com/webstore/detail/save-all-tab-urls/bgjfbcjoaghcfdhnnnnaofkjbnelkkcm?hl=en-GB

To my kowledge, there is no way of getting/accessing an url of a webpage without first switching to it.