2013-08-27 38 views
6

我在不同的機器上使用Selenium來自動化MVC Web應用程序的測試。Selenium:查找基址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"); 

有沒有更好的辦法,我能做到這一點?

+0

只是爲了確保我遵循這一點。例如:給定'http:// www.google.com/something' ...並且您希望*特別*僅僅是'http:// www.google.com'部分? – Arran

+0

當我運行應用程序時,它將轉到諸如http:// localhost:12345/Login之類的URL(這將根據機器而有所不同),然後我希望驅動程序轉到諸如http:// localhost之類的頁面:12345 /反饋。所以我只想要http:// localhost:12345/part,因爲我無法在代碼中硬編碼鏈接到它,因爲它在每臺機器上都會有所不同。 – user2184530

回答

13

解決這個問題的最好辦法是創建網址的Uri實例。

這是因爲.NET中的Uriclass已經有適合您的代碼,所以您應該使用它。我會去這樣的事情(未測試的代碼):

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 property後。

注意,有可能做了類似的事情,叫Host屬性,但是這不包括端口號,你的網站呢。不過要記住這一點。

+0

謝謝,完美的作品。 – user2184530

0

嘗試從這個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); 
2

就拿driver.Url,它折騰成一個新的System.Uri,並使用myUri.GetLeftPart(System.UriPartial.Authority)

如果你的基本URL是http://localhost:12345/Login,這將返回http://localhost:12345