Selenium ChromeDriver getPageSource()在无头模式下不起作用

时间:2018-11-15 18:18:14

标签: java selenium selenium-chromedriver

当我将ChromeDriver设置为无头模式时,无法以任何方式获取页面源。当我将驱动程序设置为非无头模式时,getPageSource()可以工作。

这是我的代码:

String pageSource = "";
try {
                System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
                System.setProperty("webdriver.chrome.silentOutput", "true");
                System.setProperty("webdriver.chrome.logfile", "/dev/null");
                java.util.logging.Logger.getLogger("org.openqa.selenium").setLevel(Level.OFF);

                ChromeOptions chromeOptions = new ChromeOptions();
                //chromeOptions.setBinary("/usr/bin/chromium");
                //chromeOptions.addArguments("--headless");
                chromeOptions.setHeadless(true);
                chromeOptions.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
                driver = new ChromeDriver(chromeOptions);

                if(driver!=null) {
                    WebDriverWait wait = new WebDriverWait(driver, 60);
                    wait.until(ExpectedConditions.visibilityOfElementLocated(By.tagName("body")));
                driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
                driver.get(link);
                pageSource = driver.getPageSource();
                driver.quit();
                }

                } catch(TimeoutException te) {
                        //te.printStackTrace();
                } catch (UnhandledAlertException eae) {
                    try {
                        Alert alert = driver.switchTo().alert();
                        String alertText = alert.getText();
                        System.out.println("Alert data: " + alertText);
                        alert.accept();
                    } catch (NoAlertPresentException e) {
                       // e.printStackTrace();
                    }
                } catch (WebDriverException wde) {
                    //wde.printStackTrace();
                }

我已经尝试通过其他方式(例如使用JavaScript)获取源,但是结果是相同的。

0 个答案:

没有答案