How do I use relative paths with the webdriver.Navigate().GotoUrl()?

ton.yeung picture ton.yeung · May 16, 2013 · Viewed 9.3k times · Source

driver.Navigate().GoToUrl("/") sets the location to "/" instead of "http://www.domain.com/"

another example would be

driver.Navigate().GoToUrl("/view1") sets the location to "/view1" instead of "http://www.domain.com/view1"

Either example would cause the browser to return with address isn't valid.

Answer

Alexander Taylor picture Alexander Taylor · Jun 21, 2016

you can use a Java URI to calculate a path relative to the current uri or domain:

import java.net.URI;

driver.get("http://example.org/one/");

// http://example.org/one/two/
driver.get(new URI(driver.getCurrentUrl()).resolve("two/").toString());

// http://example.org/one/two/three/?x=1
driver.get(new URI(driver.getCurrentUrl()).resolve("three/?x=1").toString());

// http://example.org/one/two/three/four/?y=2
driver.get(new URI(driver.getCurrentUrl()).resolve("./four/?y=2").toString());

// http://example.org/one/two/three/five/
driver.get(new URI(driver.getCurrentUrl()).resolve("../five/").toString());

// http://example.org/six
driver.get(new URI(driver.getCurrentUrl()).resolve("/six").toString());

If you're able to calculate the url without using getCurrentUrl(), it might make your code more readable.