栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用C#由javascript生成的抓取网页

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用C#由javascript生成的抓取网页

问题在于浏览器通常会执行javascript,并且会生成更新的DOM。除非您可以分析Javascript或拦截其使用的数据,否则您将需要像浏览器一样执行代码。在过去,我遇到了同样的问题,我利用selenium和PhantomJS渲染页面。呈现页面后,我将使用WebDriver客户端浏览DOM并检索所需的内容,然后发布AJAX。

从高层次上讲,这些步骤是:

  1. 已安装的硒:http : //docs.seleniumhq.org/
  2. 将硒中心作为服务启动
  3. 下载的phantomjs(无头浏览器,可以执行javascript):http ://phantomjs.org/
  4. 在webdriver模式下启动phantomjs指向selenium hub
  5. 在我的抓取应用程序中安装了webdriver客户端nuget软件包:
    Install-Package Selenium.WebDriver

这是phantomjs网络驱动程序的示例用法:

var options = new PhantomJSOptions();options.AddAdditionalCapability("IsJavascriptEnabled",true);var driver = new RemoteWebDriver( new URI(Configuration.SeleniumServerHub),         options.ToCapabilities(),         TimeSpan.FromSeconds(3)       );driver.Url = "http://www.regulations.gov/#!documentDetail;D=APHIS-2013-0013-0083";driver.Navigate();//the driver can now provide you with what you need (it will execute the script)//get the source of the pagevar source = driver.PageSource;//fully navigate the domvar pathElement = driver.FindElementById("some-id");

有关硒,phantomjs和webdriver的更多信息,可以在以下链接中找到:

http://docs.seleniumhq.org/

http://docs.seleniumhq.org/projects/webdriver/

http://phantomjs.org/

编辑:更简单的方法

似乎有一个适用于phantomjs的nuget程序包,因此您不需要集线器(我使用集群以这种方式进行大量报废):

安装网络驱动程序:

Install-Package Selenium.WebDriver

安装嵌入式exe:

Install-Package phantomjs.exe

更新的代码:

var driver = new PhantomJSDriver();driver.Url = "http://www.regulations.gov/#!documentDetail;D=APHIS-2013-0013-0083";driver.Navigate();//the driver can now provide you with what you need (it will execute the script)//get the source of the pagevar source = driver.PageSource;//fully navigate the domvar pathElement = driver.FindElementById("some-id");


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/379785.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号