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
會開啟一個新的控制檯視窗,在大多數情況下並不是真正需要的。幸運的是,我們可以隱藏視窗,甚至可以使用 PhantomJSOptions
和 PhantomJSDriverService
稍微改善效能。完整的工作示例如下:
// 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 檢視它們包含的內容以及它們的功能的簡要說明。