好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#使用Selenium+PhantomJS抓取数据

手头项目需要抓取一个用js渲染出来的网站中的数据。使用常用的httpclient抓回来的页面是没有数据。上网百度了一下,大家推荐的方案是使用phantomjs。phantomjs是一个没有界面的webkit浏览器,能够和浏览器效果一致的使用js渲染页面。selenium是一个web测试框架。使用selenium来操作phantomjs绝配。但是网上的例子多是python的。无奈,下载了python按照教程搞了一下,卡在了selenium的导入问题上。遂放弃,还是用自己惯用的c#吧,就不信c#上没有。经过半个小时的折腾,搞定(python折腾了一个小时)。记录下这篇博文,让我等搞c#的新手能用上phantomjs。

第一步:打开visual studio 2017 新建一个控制台项目,打开nuget包管理器。

第二部:搜索selenium,安装selenium.webdriver。注意:如果要使用代理的话最好安装3.0.0版本。

第三步:写下如下图所示的代码。但是执行的时候会报错。原因是找不到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被自动下载了。

好了,这样就可以开始你的数据抓取大业了。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持服务器之家!

原文链接:http://www.cnblogs.com/endlock/p/6423613.html

dy("nrwz");

查看更多关于C#使用Selenium+PhantomJS抓取数据的详细内容...

  阅读:45次