Selenium: Find the base Url

2019-04-26 15:06发布

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??

标签: c# url selenium
3条回答
Luminary・发光体
2楼-- · 2019-04-26 15:45

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.

查看更多
一纸荒年 Trace。
3楼-- · 2019-04-26 15:50

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.

查看更多
成全新的幸福
4楼-- · 2019-04-26 15:51

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);
查看更多
登录 后发表回答