zoukankan      html  css  js  c++  java
  • C# 使用HtmlAgilityPack抓取网页信息

    前几天看到一篇博文:C# 爬虫 抓取小说

    博主使用的是正则表达式获取小说的名字、目录以及内容。

     

    下面使用HtmlAgilityPack来改写原博主的代码

    在使用HtmlAgilityPack之前,可以先熟悉一下XPath:点我

    代码如下:

     1 using System;
     2 using System.IO;
     3 using System.Text;
     4 using HtmlAgilityPack;
     5 
     6 namespace HtmlAgilityPackDemo
     7 {
     8     class Program
     9     {
    10         static void Main(string[] args)
    11         {
    12             HtmlWeb htmlWeb = new HtmlWeb();
    13             HtmlDocument document = htmlWeb.Load("http://www.23us.so/files/article/html/13/13655/index.html");
    14             FileStream fs = new FileStream("无疆.txt", FileMode.Append, FileAccess.Write);
    15             StreamWriter sr = new StreamWriter(fs, Encoding.UTF8);
    16             try
    17             {
    18                 HtmlNodeCollection nodeCollection = document.DocumentNode.SelectNodes(@"//table/tr/td/a[@href]"); //  //代表获取所有
    19                 foreach (var node in nodeCollection)
    20                 {
    21                     HtmlAttribute attribute = node.Attributes["href"];
    22                     string val = attribute.Value;
    23                     var title = htmlWeb.Load(val).DocumentNode.SelectNodes(@"//h1")[0].InnerText; //文章标题
    24                     var doc = htmlWeb.Load(val).DocumentNode.SelectNodes(@"//dd[@id='contents']");//文章内容
    25                     var content = doc[0].InnerHtml.Replace("&nbsp;", "").Replace("<br>", "
    "); 
    26                     sr.WriteLine("
    " + title + "
    " + content); // 开始写入
    27                 }
    28             }
    29             catch (Exception ex)
    30             {
    31                 Console.WriteLine(ex.ToString());
    32             }
    33             finally
    34             {
    35                 sr.Close();
    36                 fs.Close();
    37             }
    38             Console.WriteLine("ok");
    39             Console.ReadKey(true);
    40 
    41 
    42         }
    43 
    44 
    45     }
    46 }
    View Code

     

    实现效果和原博主一样!

    代码仅供参考!!!

  • 相关阅读:
    多网卡环境下Eureka服务注册IP选择问题
    SpringCloud服务间调用
    Feign性能优化注意事项
    FeignClient使用
    Spring Boot优化
    nginx反向代理 强制https请求
    解决CentOS缺少共享库
    脚本加密http://www.datsi.fi.upm.es/~frosal/sources/
    tar加密
    系统用户在Samba服务器中起一个别名
  • 原文地址:https://www.cnblogs.com/liuyoung/p/7485516.html
Copyright © 2011-2022 走看看