我有一个Selenium测试套件,它运行许多测试,在每次新的测试中,它都会在我打开的任何其他窗口之上打开一个浏览器窗口。在当地工作很不和谐。有没有办法告诉硒或OS (Mac)在后台打开窗口?
当前回答
如果你正在使用谷歌Chrome驱动程序,你可以使用这段非常简单的代码(它对我有用):
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome('chromedriver2_win32/chromedriver.exe', options=chrome_options)
driver.get('https://www.anywebsite.com')
其他回答
要在没有浏览器的情况下运行,可以在headless模式下运行。
我给你们看一个Python中的例子,它现在对我有用
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("headless")
self.driver = webdriver.Chrome(executable_path='/Users/${userName}/Drivers/chromedriver', chrome_options=options)
我还在谷歌的官方网站https://developers.google.com/web/updates/2017/04/headless-chrome上给大家补充了更多的信息
下面是一个适合我的。net解决方案:
在http://phantomjs.org/download.html下载PhantomJS。
从下载文件夹中的bin文件夹中复制.exe文件,并将其粘贴到Visual Studio项目的bin调试/发布文件夹中。
使用
using OpenQA.Selenium.PhantomJS;
在你的代码中,像这样打开驱动程序:
PhantomJSDriver driver = new PhantomJSDriver();
using (driver)
{
driver.Navigate().GoToUrl("http://testing-ground.scraping.pro/login");
// Your code here
}
实现这一点的一种方法是在headless模式下运行浏览器。这样做的另一个好处是测试执行得更快。
请找到下面的代码在Chrome浏览器中设置无头模式。
package chrome;
public class HeadlessTesting {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver",
"ChromeDriverPath");
ChromeOptions options = new ChromeOptions();
options.addArguments("headless");
options.addArguments("window-size=1200x600");
WebDriver driver = new ChromeDriver(options);
driver.get("https://contentstack.built.io");
driver.get("https://www.google.co.in/");
System.out.println("title is: " + driver.getTitle());
File scrFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("pathTOSaveFile"));
driver.quit();
}
}
我的chromedriver使用Python和options.add_argument(“headless”)也有同样的问题,但后来我意识到如何修复它,所以我把它放在下面的代码中:
opt = webdriver.ChromeOptions()
opt.arguments.append("headless")
我建议使用PhantomJS。更多信息,请访问魅影官方网站。
据我所知,PhantomJS只适用于Firefox…
下载PhantomJS. exe后,您需要将其导入到您的项目中,如下图所示。
我把我的放在:common→Library→phantomjs.exe
现在,在Selenium代码中所要做的就是更改该行
browser = webdriver.Firefox()
比如
import os
path2phantom = os.getcwd() + "\common\Library\phantomjs.exe"
browser = webdriver.PhantomJS(path2phantom)
PhantomJS的路径可能会有所不同……想怎么改就怎么改:)
这个方法对我有用,我很确定它对你也有用;)
推荐文章
- Selenium WebDriver可以在后台无声地打开浏览器窗口吗?
- 我如何在python中使用selenium webdriver滚动网页?
- 如何验证一个XPath表达式在Chrome开发工具或Firefox的Firebug?
- 我如何获得当前的URL在硒Webdriver 2 Python?
- 滚动元素到视图与硒
- 在MSTest中[TearDown]和[SetUp]的替代方案是什么?
- MacOS Catalina(v 10.15.3):错误:“chromedriver”不能打开,因为开发人员无法验证。无法启动chrome浏览器
- 在Selenium中等待页面加载
- 如何选择一个下拉菜单值与硒使用Python?
- 等待页面加载Selenium WebDriver for Python
- WebDriverException:未知错误:DevToolsActivePort文件不存在,而试图启动Chrome浏览器
- 在Selenium中键入回车键
- webdriver.Dispose(), .Close()和.Quit()的区别
- 错误信息:"'chromedriver'可执行文件需要在路径中可用"
- 我如何在Selenium WebDriver (Python)中找到包含特定文本的元素?