C#丨爬虫基础

在前几天看到一片公众号的文章是关于.NET玩爬虫。

所以今天小编索性来try一下,恰好小编最近在关注房价这一块的,索性就写了一个例子抓取房产信息的。

不善言辞的小编直接给出代码吧!相信读者也等不及了。你要是觉得有用推荐一下或者评论一下吧!

using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace CatchWeb
{
    class Program
    {

        /// <summary>
        /// 
        /// 作者:haojieli
        /// 时间:2017-02-21
        /// 备注:HtmlAgilityPack例子
        /// 
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            start();
            
        }

        public static void start()
        {
            Console.WriteLine("------------------------");
            Console.WriteLine("---只可作为学习用途!");
            Console.WriteLine("---作者:haojieli");
            Console.WriteLine("---邮箱:2252487366@qq.com");
            Console.WriteLine("------------------------");
            Console.Write("是否开始抓取重庆链家的房源信息?输入Y或者N:");
            String istrue = Console.ReadLine();
            if (istrue == "Y" || istrue == "y")
            {
                String url = "http://cq.lianjia.com/xiaoqu/";
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(GetHtml(url));
                HtmlNodeCollection node = doc.DocumentNode.SelectNodes("html/body/div[4]/div[1]/ul/li");
                StreamWriter sw = File.CreateText("log.txt");
                sw.WriteLine("------------------------");
                sw.WriteLine("---只可作为学习用途!");
                sw.WriteLine("---作者:haojieli");
                sw.WriteLine("---邮箱:2252487366@qq.com");
                sw.WriteLine("------------------------");
                foreach (HtmlNode li_nodes in node)
                {
                    HtmlDocument titleDoc = new HtmlDocument();
                    titleDoc.LoadHtml(li_nodes.InnerHtml);
                    String str = titleDoc.DocumentNode.SelectNodes("//div[1]//div[1]")[0].InnerHtml;
                    HtmlDocument aDoc = new HtmlDocument();
                    aDoc.LoadHtml(str);
                    String xiaoquPrice = titleDoc.DocumentNode.SelectNodes("//div[2]//div[1]/span")[0].InnerHtml;
                    String xiaoquName = aDoc.DocumentNode.SelectNodes("//a")[0].InnerText;
                    String xiaoquUrl = aDoc.DocumentNode.SelectNodes("//a")[0].Attributes["href"].Value;
                    sw.WriteLine("小区名称:" + xiaoquName + " \r\n小区房源地址:" + xiaoquUrl + " \r\n小区平均价格:" + xiaoquPrice);
                    Console.WriteLine("小区名称:" + xiaoquName + " \r\n小区房源地址:" + xiaoquUrl + " \r\n小区平均价格:" + xiaoquPrice);
                    sw.WriteLine("----------------------------------------------------------");
                    Console.WriteLine("----------------------------------------------------------");
                }
                Console.WriteLine("---------------信息抓取完毕!");
                Console.WriteLine("---------------请在log.txt下查看抓取信息!");
                Console.WriteLine("---------------按任意键退出。");
                sw.Close();
                Console.ReadLine();
                Environment.Exit(0);
            }
            else if (istrue == "N" || istrue == "n")
            {
                Environment.Exit(0);
            }
            else
            {
                Console.WriteLine("请输入对应指令!按任意键继续。");
                Console.ReadLine();
                start();
            }
        }

        public static string GetHtml(string Url)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);
            req.Method = "GET";
            string str;
            HttpWebResponse Stream = req.GetResponse() as HttpWebResponse;
            if (Stream.CharacterSet.ToLower() == "gbk")
            {
                using (StreamReader reader = new StreamReader(Stream.GetResponseStream(), System.Text.Encoding.GetEncoding("gb2312")))
                {
                    str = reader.ReadToEnd();
                    return str;
                }
            }
            else
            {
                using (StreamReader reader = new StreamReader(Stream.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")))
                {
                    str = reader.ReadToEnd();
                    return str;
                }
            }

        } 

    }
}

  其中getHtml()是在网上找的一个处理乱码的,具体是谁写的望地址了。在此还是感谢一下!

代码也就不怎么解释了,官方文档都有!主要是对于网页分析这一块的,使用了HtmlAgilityPack 

HtmlAgilityPack的获取指定节点里面的内容是按照xpath来的 ,很简单的 自己看一下就可以了。如果想偷懒直接使用谷歌浏览器在console里面 选中你要抓取的代码内容,右键copy选项下面的Copy Xpath,具体看上面的代码 !我相信没人会看我敲的这段文字。就酱紫吧

运行效果:

 

下载exe例子

转载于:https://www.cnblogs.com/haojieli/p/6424538.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值