Selenium: Find the base Url Selenium: Find the base Url selenium selenium

Selenium: Find the base Url


The best way around this would be to create a Uri instance of the URL.

This is because the Uri class in .NET already has code in place to do this exactly for you, so you should just use that. I'd go for something like (untested code):

string url = driver.Url; // get the current URL (full)Uri currentUri = new Uri(url); // create a Uri instance of itstring baseUrl = currentUri.Authority; // just get the "base" bit of the URLdriver.Navigate().GoToUrl(baseUrl + "/Feedback"); 

Essentially, you are after the Authority property within the Uri class.

Note, there is a property that does a similar thing, called Host but this does not include port numbers, which your site does. It's something to bear in mind though.


Take the driver.Url, toss it into a new System.Uri, and use myUri.GetLeftPart(System.UriPartial.Authority).

If your base URL is http://localhost:12345/Login, this will return you http://localhost:12345.


Try this regular expression taken from this answer.

String baseUrl;Pattern p = Pattern.compile("^(([a-zA-Z]+://)?[a-zA-Z0-9.-]+\\.[a-zA-Z]+(:\d+)?/");Matcher m = p.matcher(str); if (m.matches())    baseUrl = m.group(1);