Selenium:找到基本url

我在不同的机器上使用Selenium来自动测试MVC Web应用程序。

我的问题是我无法获得每台机器的基本URL。

我可以使用以下代码获取当前url:

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

但是,当我需要导航到不同的页面时,这无济于事。

理想情况下,我可以使用以下内容导航到不同的页面:

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

我使用的可能解决方法是:

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

有没有更好的方法可以做到这一点?

解决此问题的最佳方法是创建URL的Uri实例。

这是因为.NET中的Uri 类已经有适当的代码来完成这个,所以你应该使用它。 我会选择(未经测试的代码):

 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"); 

从本质上讲,您是在Uri类中的Authority属性之后。

请注意,有一个属性做类似的事情,称为主机,但这不包括您的网站所做的端口号。 但是要记住这一点。

拿起driver.Url ,把它扔进一个新的System.Uri ,并使用myUri.GetLeftPart(System.UriPartial.Authority)

如果您的基本URL是http://localhost:12345/Login ,这将返回http://localhost:12345

试试这个答案中的正则表达式。

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