手头项目须要抓取一个用js渲染出来的网站中的数据。使用经常使用的httpclient抓回来的页面是没有数据。上网百度了一下,你们推荐的方案是使用PhantomJS。PhantomJS是一个没有界面的webkit浏览器,可以和浏览器效果一致的使用js渲染页面。Selenium是一个web测试框架。使用Selenium来操做PhantomJS绝配。可是网上的例子可能是Python的。无奈,下载了python按照教程搞了一下,卡在了Selenium的导入问题上。遂放弃,仍是用本身惯用的c#吧,就不信c#上没有。通过半个小时的折腾,搞定(python折腾了一个小时)。记录下这篇博文,让我等搞c#的新手能用上PhantomJS。python
第一步:打开visual studio 2017 新建一个控制台项目,打开nuget包管理器。web
第二部:搜索Selenium,安装Selenium.WebDriver。注意:若是要使用代理的话最好安装3.0.0版本。c#
第三步:写下以下图所示的代码。可是执行的时候会报错。缘由是找不到PhantomJS.exe。这时候能够去下载一个,也能够继续看第四步。浏览器
using OpenQA.Selenium; using OpenQA.Selenium.PhantomJS; using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { var url = "http://www.baidu.com"; IWebDriver driver = new PhantomJSDriver(GetPhantomJSDriverService()); driver.Navigate().GoToUrl(url); Console.WriteLine(driver.PageSource); Console.Read(); } private static PhantomJSDriverService GetPhantomJSDriverService() { PhantomJSDriverService pds = PhantomJSDriverService.CreateDefaultService(); //设置代理服务器地址 //pds.Proxy = $"{ip}:{port}"; //设置代理服务器认证信息 //pds.ProxyAuthentication = GetProxyAuthorization(); return pds; } } }
第四步:打开nuget安装Selenium.PhantomJS.WebDriver包。服务器
第五步:运行。能够看到phantomjs.exe被自动下载了。框架
好了,这样就能够开始你的数据抓取大业了。测试