最近在學(xué)習(xí)webdriver,順便把遇到的問題記在這里凡人,以便日后查閱撒会,并分享給遇到相同問題的人紧卒。
問題:運(yùn)行seleniumhq.org網(wǎng)站上的例子奸腺。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Selenium2Example {
public static void main(String[] args) {
// Create a new instance of the Firefox driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Alternatively the same thing can be done like this
// driver.navigate().to("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("cheese!");
}
});
// Should see: "cheese! - Google Search"
System.out.println("Page title is: " + driver.getTitle());
//Close the browser
driver.quit();
}
}
報(bào)如下錯誤
Exception in thread "main"
org.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH.
Make sure firefox is installed. OS appears to be: XP
Build info: version: '2.18.0', revision: '15704', time: '2012-01-27 17:37:17'
System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1',
java.version: '1.6.0_23'
看這個報(bào)錯應(yīng)該是firefox安裝路徑不是默認(rèn)路徑餐禁。
解決方法:方法1、最簡單的重新安裝firefox到默認(rèn)路徑洋机。
方法2、直接用System.setPropert方法設(shè)置webdriver.firefox.bin的值洋魂,如
System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");
方法3绷旗、 用FirefoxBinary類和public FirefoxDriver(FirefoxBinary
binary, FirefoxProfile profile)這個構(gòu)造方法,直接上代碼
File pathToFirefoxBinary = new File("D:\\Program Files\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxbin = new FirefoxBinary(pathToFirefoxBinary);
WebDriver driver = new FirefoxDriver(firefoxbin,null);//這里使用這個構(gòu)造方法副砍。
應(yīng)該還可以在環(huán)境變量里面設(shè)置firefox的路徑也可以衔肢,有興趣的可以試一下。
注:有人可能會不知道webdriver.firefox.bin豁翎,可以看一下源碼角骤,其中
org.openqa.selenium.firefox.internal.Executable.locateFirefoxBinaryFromSystemProperty()
方法第一句
String binaryName = System.getProperty("webdriver.firefox.bin");
說明默認(rèn)的時(shí)候取的就是這個值,重新設(shè)置一下心剥。