我使用Selenium PhantomJS Webdriver在我的c#应用程序中抓取页面。我经常使用控制台,所以我想关闭它不断输出的INFO消息。有人有同样的问题吗?
我认为这个字符串必须添加到黄蜂的答案:
service.HideCommandPromptWindow = true;
static IWebDriver CreateInfolessPhantom(string logFilePath)
{
PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService();
service.LogFile = logFilePath;
service.HideCommandPromptWindow = true;
return new PhantomJSDriver(service);
}
我找到了一个解决方法,它帮助了我,尽管它不是很漂亮。它清除每次启动webdriver时创建的信息。我使用一个简单的方法来返回一个新的驱动程序,在这个方法中,我调用一个方法来清除在控制台中创建的行,并将控制台光标定位在下一行。
public static IWebDriver GetDriver()
{
IWebDriver driver = new PhantomJSDriver();
ClearCurrentConsoleLine();
return driver;
}
public static void ClearCurrentConsoleLine()
{
int pos = Console.CursorTop;
for (int i = 0; i < 20; i++)
{
Console.SetCursorPosition(0, Console.CursorTop - i);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0,pos);
}
Console.SetCursorPosition(0,Console.CursorTop-19);
}
下面的代码对我来说很好:
var driverService = PhantomJSDriverService.CreateDefaultService(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
driverService.SuppressInitialDiagnosticInformation = true;
driverService.AddArgument("--webdriver-loglevel=NONE");
driver = new PhantomJSDriver(driverService);
这是我第一次提交代码,如果它对你有帮助,请投票,如果你有改进,请添加评论。
using System;
using System.Collections.Generic;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.PhantomJS;
namespace PhantomJSExample
{
class Program
{
static void Main(string[] args)
{
string logFilePath = @"C:UsersUsernameDesktopoutputLog.log";
IWebDriver driver = CreateInfolessPhantom(logFilePath);
}
// Prepares a PhantomJS driver that does not dislay its logs in the console window.
// The trade-off is, you have to give it a file path to output to instead.
static IWebDriver CreateInfolessPhantom(string logFilePath)
{
PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService();
service.LogFile = logFilePath;
return new PhantomJSDriver(service);
}
}
}