java 使用硒运行的无头 Chrome
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47067188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Headless Chrome run with selenium
提问by ses
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);
fails as:
失败为:
Exception in thread "main" org.openqa.selenium.WebDriverException: Unable to parse remote response:
Not Found
线程“main” org.openqa.selenium.WebDriverException 中的异常:无法解析远程响应:
未找到
Any idea why?
知道为什么吗?
Followed: How to connect to Chromium Headless using Selenium
回答by Davide Patti
What are the versions of your Chrome browser, chromedriver and Selenium? I tried with:
您的 Chrome 浏览器、chromedriver 和 Selenium 的版本是什么?我试过:
- Chrome Version 62.0.3202.75 (Official Build) (64-bit)
- chromedriver 2.33
- Selenium 3.6.0
- Chrome 版本 62.0.3202.75(官方版本)(64 位)
- 铬驱动程序 2.33
- 硒 3.6.0
The following code:
以下代码:
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());
Note: In current versions of Selenium and ChromeDriver replace:
注意:在当前版本的 Selenium 和 ChromeDriver 中替换:
chromeOptions.addArguments("--headless");
with
和
chromeOptions.setHeadless(true);
Ref: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/chrome/ChromeOptions.html#setHeadless-boolean-Also you must set Window size otherwise it renders in mobile mode and you may not get certain elements in the page.
参考:https: //seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/chrome/ChromeOptions.html#setHeadless-boolean-此外,您必须设置窗口大小,否则它会在移动模式下呈现,您可能无法获取页面中的某些元素。
chromeOptions.addArguments("--window-size=1200x600");
Tested on chromedriver 2.42.591071 with Selenium 3.14.0
在 chromedriver 2.42.591071 和 Selenium 3.14.0 上测试
The output:
输出:
The Internet
Take a look to Getting Started with Headless Chromeabout the browser support versions.
请查看Headless Chrome 入门,了解浏览器支持版本。
回答by fahim reza
options.addArguments("headless");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
This worked for me. Chromedriver Version:2.37
这对我有用。Chromedriver 版本:2.37