Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium: Find the base Url

Tags:

c#

url

selenium

I'm using Selenium on different machines to automate testing of a MVC Web application.

My problem is that I can't get the base url for each machine.

I can get the current url using the following code:

IWebDriver driver = new FirefoxDriver();
string currentUrl = driver.Url;

But this doesn't help when I need to navigate to a different page.

Ideally I could just use the following to navigate to different pages:

driver.Navigate().GoToUrl(baseUrl+ "/Feedback");
driver.Navigate().GoToUrl(baseUrl+ "/Home");

A possible workaround I was using is:

string baseUrl = currentUrl.Remove(22); //remove everything from the current url but the base url
driver.Navigate().GoToUrl(baseUrl+ "/Feedback");

Is there a better way I could do this??

like image 893
user2184530 Avatar asked Aug 27 '13 12:08

user2184530


2 Answers

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 it
string baseUrl = currentUri.Authority; // just get the "base" bit of the URL
driver.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.

like image 107
Arran Avatar answered Oct 21 '22 05:10

Arran


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.

like image 33
Alex Avatar answered Oct 21 '22 07:10

Alex