Selenium: Find Base Url

I use Selenium on different machines to automate testing an MVC web application.

My problem is that I cannot 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 does not help when I need to go to another page.

Ideally, I could just use the following to go to different pages:

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

A possible workaround that I used:

 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 to do this?

+6
source share
3 answers

The best way around this is to instantiate the Uri url.

This is because the Uri class in .NET already has code to do this for you, so you should just use it. I would go for something like (unverified 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 permissions property in the Uri class.

Please note that there is a property that does a similar thing called Host , but this does not include the port numbers that your site does. This is something to keep in mind though.

+13
source

Take driver.Url , move it to the 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 .

+2
source

Try this regex taken from this.

 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); 
0
source

Source: https://habr.com/ru/post/952588/


All Articles