How do I get current URL in Selenium Webdriver 2 Python?
Asked Answered
S

5

246

I'm trying to get the current url after a series of navigations in Selenium. I know there's a command called getLocation for ruby, but I can't find the syntax for Python.

Socialminded answered 13/4, 2013 at 7:20 Comment(2)
Selenium doc explains it all :selenium.dev/docs/site/en/webdriver/browser_manipulation/…Thorr
@Thorr this link Not working. please update itYoumans
V
445

Use current_url element for Python 2:

print browser.current_url

For Python 3 and later versions of selenium:

print(driver.current_url)
Ventriloquize answered 13/4, 2013 at 8:53 Comment(5)
or, also known as driver.current_urlGrover
suppose, there is a chain of page p1->p2->p3 where p2 on the basis of credentials in p1 is redirecting to either p1 or p3. How to get the url just after clicking which I am not able to understand. selenium doesnot stop at that page and is directly giving me the url of p3. how to go for this?Uvula
@Uvula #35593102Marylou
more importantly, where is this documented on selenium-python.readthedocs.io ?Boffin
@RobertJohnstone: selenium-python.readthedocs.io/…Sunfish
G
99

According to this documentation (a place full of goodies:)):

driver.current_url

or, see official documentation: https://www.selenium.dev/documentation/en/webdriver/browser_manipulation/#get-current-url

Gosselin answered 12/3, 2015 at 8:8 Comment(0)
S
7

Selenium2Library has get_location():

import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()
Schmuck answered 2/8, 2013 at 7:53 Comment(0)
F
2

Another way to do it would be to inspect the url bar in chrome to find the id of the element, have your WebDriver click that element, and then send the keys you use to copy and paste using the keys common function from selenium, and then printing it out or storing it as a variable, etc.

Fechner answered 2/4, 2019 at 23:42 Comment(0)
S
0

There are multiple ways to get the current URL via the driver:

driver.current_url
driver.execute_script("return document.URL;")
driver.execute_script("return document.location.href;")
driver.execute_script("return window.location.href;")

(Note that there are differences between the various JS variables for this, as specified here: https://mcmap.net/q/118960/-difference-between-document-url-and-location-href)

In some cases, you might not want the full URL, but the origin instead:

driver.execute_script("return window.location.origin;")

For example, on stackoverflow pages (such as this one), the origin is https://stackoverflow.com. (Useful for when you don't want the full URL.)

There are also popular Python frameworks, such as SeleniumBase, with built-in methods for returning the URL, (or the origin):

self.get_current_url()    # SeleniumBase only
self.get_origin()         # SeleniumBase only
Sarena answered 27/6, 2023 at 21:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.