抓取网站时隐藏Chrome窗口



我已经在网络爬虫上工作了一段时间。现在一切正常,但我想为我的程序添加最后的润色,并在进程运行时隐藏 Chrome 窗口不可见。

我试图将这个添加到我的代码中:

var chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true;
return new ChromeDriver(chromeDriverService,  new ChromeOptions());

但是没有成功。有人可以给我一个提示,应该如何添加这个隐藏命令才能正常工作吗?我应该如何修改当前代码以实现后台运行?

这是我的代码:

using System.Linq;
using OpenQA.Selenium.Chrome;
namespace WebDriverTest
{
class Program
{
static void Main(string[] args)
{
// Initialize the Chrome Driver
using (var driver = new ChromeDriver())
{
// Go to the home page
driver.Navigate().GoToUrl("xxx.com");
driver.Manage().Timeouts().ImplicitWait = System.TimeSpan.FromSeconds(15);
// Get the page elements
var userNameField = driver.FindElementById("loginForm:username");
var userPasswordField = driver.FindElementById("loginForm:password");
var loginButton = driver.FindElementById("loginForm:loginButton");
// Type user name and password
userNameField.SendKeys("username");
userPasswordField.SendKeys("password");
// and click the login button
loginButton.Click();
// Extract the text and save it into result.txt
// var result = driver.FindElementByXPath("//div[@id='case_login']/h3").Text;
// File.WriteAllText("result.txt", result);
// Take a screenshot and save it into screen.png
driver.GetScreenshot().SaveAsFile(@"screen.png", OpenQA.Selenium.ScreenshotImageFormat.Png);
}
}
}
}

您是否尝试过添加:

var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("headless");

好的,经过一些调查,它应该是:

using System.Linq;
using OpenQA.Selenium.Chrome;
using Scripting;
using System.IO;
namespace WebDriverTest
{
class Program
{
static void Main(string[] args)
{
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("headless");
// Initialize the Chrome Driver
using (var driver = new ChromeDriver(chromeOptions))
{
// Go to the home page
driver.Navigate().GoToUrl("xxx.com");
driver.Manage().Timeouts().ImplicitWait = System.TimeSpan.FromSeconds(15);
// Get the page elements
var userNameField = driver.FindElementById("loginForm:username");
var userPasswordField = driver.FindElementById("loginForm:password");
var loginButton = driver.FindElementById("loginForm:loginButton");
// Type user name and password
userNameField.SendKeys("username");
userPasswordField.SendKeys("password");
// and click the login button
loginButton.Click();
// Extract the text and save it into result.txt
// var result = driver.FindElementByXPath("//div[@id='case_login']/h3").Text;
// File.WriteAllText("result.txt", result);
// Take a screenshot and save it into screen.png
driver.GetScreenshot().SaveAsFile(@"screen.png", OpenQA.Selenium.ScreenshotImageFormat.Png);
}
}
}
}

最新更新