Selenium:查找基本 URL [英] Selenium: Find the base Url

查看:40
本文介绍了Selenium:查找基本 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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

这是因为 .NET 已经有代码可以完全为您执行此操作,因此您应该使用它.我会去寻找类似(未经测试的代码):

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

本质上,您是在 中的 权威属性Uri 类.

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

注意,有一个属性做类似的事情,叫做 Host 但这不包括您的站点所包含的端口号.不过,这是需要牢记的.

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.

这篇关于Selenium:查找基本 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆