简体   繁体   中英

How set relative path in driver.get() method in selenium?

In Selenium I can navigate to a URL using driver.get(DesireURL) method. If I have to navigate to a local HTML file I can use

driver.get("C://what ever the location of my file");

But if my HTML file located to in my project resource directory like resources/HTML/file.html.

I am using this code in Ubuntu and windows so a don't use absolute path.
How can I browse that file like driver.get(“resources/HTML/file.html”)?

尝试这个:

driver.get("file:///C://what ever the location of my file");

If your file at any location you can use like this, simply use file:///C:/Sankalp/test.html address in get("") method

Try sample code:

public class Hello {

public static void main(String[] args) {

    System.setProperty("webdriver.gecko.driver", "C:/Users/sankalp.gupta/Desktop/JAVASEL/geckodriver.exe");
    WebDriver driver=new FirefoxDriver();
    driver.get("file:///C:/Sankalp/test.html");  //replace it with your path
    System.out.println(driver.getCurrentUrl());
}

}

Firstly create a AppConstant class where all the constant resources path are specified.

 /*
 * used to get the path of necessary resources 
 */
  public class AppConstant {

  // prevents instantiation
  private AppConstant () { 

 } 

  public static final String CURRENT_DIR = System.getProperty("user.dir");
  public static final String APP_RESOURCE = CURRENT_DIR+"/resources/";  
 }

Then use the resource path as follows

 driver.get("file:"+AppConstant.APP_RESOURCE+"HTML/file.html");

EDIT: You can also verify by using this if you do not want to create another class

String htmlLocation = "file:"+System.getProperty("user.dir")+"/resources/HTML/Table.html";
driver.get(htmlLocation);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM