微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java-用硒运行无头Chrome

        System.setProperty("webdriver.chrome.driver", "/usr/bin/google-chrome");

        final ChromeOptions chromeOptions = new ChromeOptions();
        //chromeOptions.addArguments("headless");
        chromeOptions.addArguments("window-size=1200x600");

        final DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
        desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);


        final URL url = new URL("https://the-internet.herokuapp.com/login");
        final WebDriver driver = new RemoteWebDriver(url, desiredCapabilities);

失败为:

Exception in thread “main” org.openqa.selenium.WebDriverException:
Unable to parse remote response:

Not Found

知道为什么吗?

已追踪:How to connect to Chromium Headless using Selenium

解决方法:

您的Chrome浏览器,chromedriver和Selenium有哪些版本?我尝试过:

> Chrome版本62.0.3202.75(官方内部版本)(64位)
> chromedriver 2.33
>硒3.6.0

如下代码

    System.setProperty("webdriver.chrome.driver", "/pathTo/chromedriver);

    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.addArguments("--headless");

    ChromeDriver driver = new ChromeDriver(chromeOptions);
    driver.get("https://the-internet.herokuapp.com/login");
    System.out.println(driver.getTitle());

注意:在当前版本的Selenium和ChromeDriver中,替换为:

    chromeOptions.addArguments("--headless");

    chromeOptions.setHeadless(true);

参考:https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/chrome/ChromeOptions.html#setHeadless-boolean-
另外,您必须设置“窗口大小”,否则它将在移动模式下呈现,并且您可能无法在页面中获得某些元素.

    chromeOptions.addArguments("--window-size=1200x600");

在带有硒3.14.0的chromedriver 2.42.591071上测试

输出

The Internet

查看有关浏览器支持版本的Getting Started with Headless Chrome.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐