How can one get the url of a new opened tab by the first website that was running in Selenium Python

Viewed 35

I am trying to get the URL of the newly opened tab so I can work on it and find elements in that tab. How can one get a URL of a new opened tab that was opened by the website on click of a button using selenium in python.

1 Answers

In general Selenium automation, we first switch to newly opened tab and then we can get the URL and we can then interact with the element.

for switching to new tab, you can use the below code:

original_win_handle = driver.current_window_handle
# code to click on the first page and now expecting a new tab to be opened
all_win_handles = driver.window_handles
driver.switch_to.window(all_win_handles[1])

and now you've switched it successfully, you can get the URL by running the below code:

print(driver.current_url)
Related