To enhance my understanding of working with PhantomJS, I decided to experiment with a simple Google search today. Here are the steps I took:
- Open Google (successful)
- Take a screenshot (to confirm the page has loaded) (successful)
- Attempt to input "Hello" into the search field (unsuccessful)
Here is the code I used:
System.setProperty("phantomjs.binary.path", "webdriver/phantomjs.exe");
WebDriver driver = new PhantomJSDriver();
driver.get("http://google.com");
Thread.sleep(20000);
File file = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileCopyUtils.copy(file, new File("C:/Users/username/Desktop/screenshot.jpg"));
Actions a = new Actions(driver);
a.moveToElement(driver.findElement(By.xpath("//*[@id=\"lst-ib\"]"))).click().perform();
a.sendKeys("Hello").perform();
I tried clicking on the textfield and entering "Hello," but encountered an error - "NoSuchElementException," not "NullPointerException."
org.openqa.selenium.NoSuchElementException: {"errorMessage":"Unable to find element with xpath
'//[@id=\"lst-ib\"]'","request":{"headers":{"Accept-Encoding":"gzip,deflate","Connection":"Keep-Alive","Content-Length":"47","Content-Type":"application/json;
charset=utf-8","Host":"localhost:39266","User-Agent":"Apache-HttpClient/4.5.1 (Java/1.8.0_66)"},"httpVersion":"1.1","method":"POST","post":"{\"using\":\"xpath\",\"value\":\"//[@id=\\"lst-ib\\"]\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/1fae7fb0-3651-11e7-a707-9fe5bd25a173/element"}}
Command duration or timeout: 303 milliseconds For documentation on
this error, please visit:
at
[error details]...
Caused by: org.openqa.selenium.remote.ScreenshotException: [additional info]
at [error details]...
Caused by: org.openqa.selenium.NoSuchElementException: [details]
For more information on this error, please visit:
Update 12.05.2017: I came across a solution here:
Using findElementBy.name("q") proved to be effective in locating the WebElement.