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

     

    实现效果和原博主一样!

    代码仅供参考!!!

  • 相关阅读:
    小程序开发过程中遇到的问题
    Windows 常用命令与快捷键
    前端开发中遇到的问题记录
    判断当前页面是否在微信中
    js学习导图
    一篇不错的 文章
    flex 布局
    微信客户端sdk使用前的 授权签名
    elementUI+vue-cli el-table=》excel
    rem适配
  • 原文地址:https://www.cnblogs.com/liuyoung/p/7485516.html
Copyright © 2011-2022 走看看