C# , htmlAgilityPack,乱码的问题,GB2312,爬虫乱码,byte编码GB2312

学习htmlAgilityPack文档时,尝试直接用官网给的代码,将网址修改为百度搜索风云榜的网址,出现各种问号乱码.

var html = @"http://html-agility-pack.net/";
HtmlWeb web = new HtmlWeb();
var htmlDoc = web.Load(html);
var node = htmlDoc.DocumentNode.SelectSingleNode("//head/title");
Console.WriteLine("Node Name: " + node.Name + "\n" + node.OuterHtml);

查阅资料之后发现,这个包是法国人写的,默认解码是按法语.解决思路如下:

参考文档

以byte数组格式获取html
从byte转码至其他编码形式
解析html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using System.Net.Http;


namespace htmlAgilitypack
{
    class Program
    {
        static readonly HttpClient client = new HttpClient();
        static async Task Main()
        {
            // Call asynchronous network methods in a try/catch block to handle exceptions.
            try
            {
              //以byte[]获取html
                byte[] response1= await client.GetByteArrayAsync("http://top.baidu.com/buzz?b=1&fr=topindex");
                //foreach(byte i in response1)
                //{
                //    Console.Write(i);
                //}
                //Console.WriteLine("\n");

                //将byte[]重新编码成GB2312;
                string temp = Encoding.GetEncoding("GB2312").GetString(response1);

                //解析html,并输入
                HtmlDocument html = new HtmlDocument();
                html.LoadHtml(temp);
                var node = html.DocumentNode.SelectNodes("//a[@class=\"list-title\"]");
                foreach(var t in node)
                {
                    Console.WriteLine(t.InnerText);
                }              
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
            finally
            {
                Console.Read();
            }
        }
    }
}

结果如下,成功获取百度搜索风云榜信息
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值