PhantomJS C.

PhantomJS 是一个功能齐全的无头网络浏览器**,**支持 JavaScript。

在开始之前,你需要下载 PhantomJS 驱动程序,并确保将其放在代码的开头:

using OpenQA.Selenium;
using OpenQA.Selenium.PhantomJS;

好的,现在进行初始化:

var driver = new PhantomJSDriver();

这将只是创建一个 PhantomJSDriver 类的新实例。然后,你可以像使用每个 WebDriver 一样使用它,例如:

using (var driver = new PhantomJSDriver())
{
    driver.Navigate().GoToUrl("http://stackoverflow.com/");

    var questions = driver.FindElements(By.ClassName("question-hyperlink"));

    foreach (var question in questions)
    {
        // This will display every question header on StackOverflow homepage.
        Console.WriteLine(question.Text);
    }
}

这很好用。但是,你可能遇到的问题是,在使用 UI 时,PhantomJS 会打开一个新的控制台窗口,在大多数情况下并不是真正需要的。幸运的是,我们可以隐藏窗口,甚至可以使用 PhantomJSOptionsPhantomJSDriverService 稍微改善性能。完整的工作示例如下:

// Options are used for setting "browser capabilities", such as setting a User-Agent
// property as shown below:
var options = new PhantomJSOptions();
options.AddAdditionalCapability("phantomjs.page.settings.userAgent", 
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0");

// Services are used for setting up the WebDriver to your likings, such as
// hiding the console window and restricting image loading as shown below:
var service = PhantomJSDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
service.LoadImages = false;

// The same code as in the example above:
using (var driver = new PhantomJSDriver(service, options))
{
    driver.Navigate().GoToUrl("http://stackoverflow.com/");

    var questions = driver.FindElements(By.ClassName("question-hyperlink"));

    foreach (var question in questions)
    {
        // This will display every question header on StackOverflow homepage.
        Console.WriteLine(question.Text);
    }
}

专业提示:点击一个类(例如 PhantomJSDriverService),然后按 F12 查看它们包含的内容以及它们的功能的简要说明。