欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#打开浏览器并全屏(运行打开浏览器命令)

程序员文章站 2023-11-29 22:17:58
基于c#.net+phantomjs+sellenium的高级网络爬虫程序。可执行javascript代码、触发各类事件、操纵页面dom结构、甚至可以移除不喜欢的css样式。很多网站都用ajax动态加...

基于c#.net+phantomjs+sellenium的高级网络爬虫程序。可执行javascript代码、触发各类事件、操纵页面dom结构、甚至可以移除不喜欢的css样式。

很多网站都用ajax动态加载、翻页,比如携程网的评论数据。如果是用之前那个简单的爬虫,是很难直接抓取到所有评论数据的,我们需要去分析那漫天的javascript代码寻找api数据接口,还要时刻提防对方增加数据陷阱或修改api接口地。

如果通过高级爬虫,就可以完全无视这些问题,无论他们如何加密javascript代码来隐藏api接口,最终的数据都必要呈现在网站页面上的dom结构中,不然普通用户也就没法看到了。所以我们可以完全不分析api数据接口,直接从dom中提取数据,甚至都不需要写那复杂的正则表达式。

主要特性

  • 支持ajax请求事件的触发及捕获;
  • 支持异步并发抓取;
  • 支持自动事件通知;
  • 支持代理切换;
  • 支持操作cookies;

运行截图

  • 抓取酒店数据
  • 抓取评论数据

示例代码

 /// <summary>
    /// 抓取酒店评论
    /// </summary>
	static void main(string[] args)
    {
        var hotelurl = "http://hotels.ctrip.com/hotel/434938.html";
        var hotelcrawler = new strongcrawler();
        hotelcrawler.onstart += (s, e) =>
        {
            console.writeline("爬虫开始抓取地址:" + e.uri.tostring());
        };
        hotelcrawler.onerror += (s, e) =>
        {
            console.writeline("爬虫抓取出现错误:" + e.uri.tostring() + ",异常消息:" + e.exception.tostring());
        };
        hotelcrawler.oncompleted += (s, e) =>
        {
            hotelcrawler(e);
        };
        var operation = new operation
        {
            action = (x) => {
                //通过selenium驱动点击页面的“酒店评论”
                x.findelement(by.xpath("//*[@id='commenttab']")).click();
            },
            condition = (x) => {
                //判断ajax评论内容是否已经加载成功
                return x.findelement(by.xpath("//*[@id='commentlist']")).displayed && x.findelement(by.xpath("//*[@id='hotel_info_comment']/div[@id='commentlist']")).displayed && !x.findelement(by.xpath("//*[@id='hotel_info_comment']/div[@id='commentlist']")).text.contains("点评载入中");
            },
            timeout = 5000
        };

        hotelcrawler.start(new uri(hotelurl), null, operation);//不操作js先将参数设置为null

        console.readkey();
    }

github:https://github.com/microfisher/strong-web-crawler