我使用selenium web driver java编写代码来搜索学校并从搜索中获取第一个url。没有PhantomJS,我的代码工作正常。但是因为我想使用无头浏览器,尝试使用以下代码进行更改。
WebElement element = driver.findElement(By.name("q"));
PhantomJS在下面的代码中找不到这个元素“driver.findElement(By.name("q"));
”,我也尝试使用id,但没有成功。
Capabilities caps = new DesiredCapabilities();
((DesiredCapabilities) caps).setJavascriptEnabled(true);
((DesiredCapabilities)caps).setCapability("takesScreenshot", true);
((DesiredCapabilities) caps).setCapability( PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,"C:/Softwares/phantomjs-2.5.0-beta-windows/phantomjs-2.5.0.beta-windows/bin/phantomjs.exe");
// Initialize browser
WebDriver driver = new PhantomJSDriver(caps);
// And now use this to visit Google
driver.get("https://www.google.com");
// Maximize browser
driver.manage().window().maximize();
// find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
String searchSchool = "Bay High School"
// enter something to search for
element.sendKeys(searchSchool);
System.out.println("school name is "+ searchSchool);
// now submit the form
element.submit();
Thread.sleep(500);
WebElement click = driver.findElement(By.name("btnG"));
click.click();
Thread.sleep(2000);
List<WebElement> listings = driver.findElements(By.tagName("div").xpath("//cite[@class='_Rm']"));
listings.size();