Search code examples
pythonseleniumwebdrivergeturl

How to find URL of web page opened by clicking link?


My scenario is: I opened a webpage (it has different links) and clicked on a link randomly. Now I want to get the URL of that webpage opened.

I searched a lot and found the same answer everywhere which I tried.

driver.get(url)
driver.current_url

It every time returns me the URL of the main webpage, not that which is opened by clicking a link randomly. What I have observed is, such is happening because on clicking link new webpage opens up in a new tab and current_url returns me URL of the page that is on the first tab. Any solution to this problem?


Solution

  • In order to work with new tab you have to switch driver to it.

    You can use Selenium methods to check current window and move to another one:

    driver.window_handles
    

    to find a list of window handles and after try to switch using following methods.

    - driver.switch_to.active_element      
    - driver.switch_to.default_content
    - driver.switch_to.window