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.
-
Selenium doc explains it all :selenium.dev/docs/site/en/webdriver/browser_manipulation/…anandharshan– anandharshan2020-06-29 04:05:24 +00:00Commented Jun 29, 2020 at 4:05
-
@anandharshan this link Not working. please update itTipVisor– TipVisor2022-06-15 12:14:07 +00:00Commented Jun 15, 2022 at 12:14
6 Answers
Use current_url element for Python 2:
print browser.current_url
For Python 3 and later versions of selenium:
print(driver.current_url)
5 Comments
driver.current_urlAccording 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
Comments
To get the current URL of the page in Selenium, you can use the driver.current_url property. Here's an example:
from selenium import webdriver
# Initialize the driver (replace with your browser driver)
driver = webdriver.Chrome()
# Open a webpage
driver.get("https://example.com")
# Get the current URL
current_url = driver.current_url
print("Current URL:", current_url)
# Close the driver
driver.quit()
Comments
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://stackoverflow.com/a/5388084/7058266)
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