国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

解決網(wǎng)爬工具爬取頁面信息出現(xiàn)亂碼的問題

2019-11-17 05:49:11
字體:
供稿:網(wǎng)友
問題:
   網(wǎng)爬工具中自動搜集頁面信息時,有的頁面出現(xiàn)了出現(xiàn)亂碼現(xiàn)象
原因:
   讀取頁面信息是使用了錯誤的編碼類型。C#.NET從現(xiàn)在的類中獲取得來的編碼信息有時是錯誤的,本人認(rèn)為對不是asp.net的應(yīng)用程序,它讀過來的編碼信息都是錯誤的。
解決:
   思路:必須先在運(yùn)行時獲取得該頁面的編碼,再去讀取頁面的內(nèi)容,這樣得來的頁面內(nèi)容才不會出現(xiàn)亂碼現(xiàn)象。
   方法:
   1:使用ASCII編碼去讀取頁面內(nèi)容。
   2:使用正則表達(dá)式從讀取的頁面內(nèi)容中篩選出頁面的編碼信息。上個步驟獲取的頁面信息可能會有亂碼。但Html標(biāo)志是正確的,所有可以從HTML標(biāo)志中得到編碼的信息。
   3.用正確的編碼類型去讀取頁面信息。
   假如哪位有更好的方法,請多賜教啊!   
   下面附上代碼:    代碼演示
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;
using System.IO;
using System.Text.RegularEXPRessions;
namespace charset
{
    class Program
    {
       
        static void Main(string[] args)
        {
            string url = "http://www.gdqy.edu.cn";
            GetCharset1(url);
            GetChartset2(url);            Console.Read();
        }
        // 通過HttpWebResponse直接獲取頁面編碼
        static void GetCharset1(string url)
        {
            try
            {
                WebRequest webRequest = WebRequest.Create(url);
                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();                string charset = webResponse.CharacterSet;
                string contentEncoding = webResponse.ContentEncoding;
                string contentType = webResponse.ContentType;                Console.WriteLine("context type:{0}", contentType);                Console.WriteLine("charset:{0}", charset);                Console.WriteLine("content encoding:{0}", contentEncoding);

                //測試或取頁面是否出現(xiàn)亂碼
                //Console.WriteLine(getHTML(url,charset));
               
            }
            catch (UriFormatException ex)
            {                Console.WriteLine(ex.Message);
            }
            catch(WebException ex)
            {
           
                Console.WriteLine(ex.Message);
            }
           
           
                     }
        //使用正則表達(dá)式獲取頁面編碼
        static void GetChartset2(string url)
        {            try
            {
                string html = getHTML(url,Encoding.ASCII.EncodingName);
                Regex reg_charset = new Regex(@"charset/b/s*=/s*(?<charset>[^""]*)");
                string enconding = null;
                if (reg_charset.IsMatch(html))
                {
                    enconding = reg_charset.Match(html).Groups["charset"].Value;
                    Console.WriteLine("charset:{0}",enconding);
                }
                else

                {
                    enconding = Encoding.Default.EncodingName;
                }
                //測試或取頁面是否出現(xiàn)亂碼
                //Console.WriteLine(getHTML(url,enconding));
             }
            catch (UriFormatException ex)
            {                Console.WriteLine(ex.Message);
            }
            catch(WebException ex)
            {
           
                Console.WriteLine(ex.Message);
            }
       
        }
        //讀取頁面內(nèi)容方法
        static string  getHTML(string url,string encodingName)
        {            try
            {
                WebRequest webRequest = WebRequest.Create(url);
                WebResponse webResponse = webRequest.GetResponse();
                Stream stream = webResponse.GetResponseStream();
                StreamReader sr = new StreamReader(stream, Encoding.GetEncoding(encodingName));
                string html = sr.ReadToEnd();
                return html;
            }
            catch (UriFormatException ex)
            {                Console.WriteLine(ex.Message);

                return null;
            }
            catch (WebException ex)
            {                Console.WriteLine(ex.Message);
                return null;
            }
        }
       
    }
} http://www.gdqy.edu.cn頁面的使用的編碼格式是:gb2312
第一個方法顯示的內(nèi)容是:
context type:text/html
charset:ISO-8859-1
content encoding:
第二個方法顯示的內(nèi)容是:
charset:gb2312所以第一個方法獲取的信息是錯誤的,第二個方法是對的。
為什么第一個方法獲取的的編碼格式是:ISO-8859-1呢?
我用Reflector反射工具獲取了CharacterSet屬性的源代碼,從中不難看出其原因。假如能獲取出ContentType屬性的源代碼就不以看出其出錯的原因了,但是搞了許久都沒找出,假如那位那補(bǔ)上,那就太感謝了。
下面我附上Reflector反射工具獲取了CharacterSet屬性的源代碼,有愛好的朋友看一看。 CharacterSet源碼
public string CharacterSet
{
      get
      {
            this.CheckDisposed();
            string text1 = this.m_HttpResponseHeaders.ContentType;
            if ((this.m_CharacterSet == null) && !ValidationHelper.IsBlankString(text1))
            {
                  this.m_CharacterSet = string.Empty;
                  string text2 = text1.ToLower(CultureInfo.InvariantCulture);
                  if (text2.Trim().StartsWith("text/"))
                  {
                        this.m_CharacterSet = "ISO-8859-1";
                  }
                  int num1 = text2.IndexOf(";");
                  if (num1 > 0)
                  {

                        while ((num1 = text2.IndexOf("charset", num1)) >= 0)
                        {
                              num1 += 7;
                              if ((text2[num1 - 8] == ';') (text2[num1 - 8] == ' '))
                              {
                                    while ((num1 < text2.Length) && (text2[num1] == ' '))
                                    {
                                          num1++;
                                    }
                                    if ((num1 < (text2.Length - 1)) && (text2[num1] == '='))
                                    {
                                          num1++;
                                          int num2 = text2.IndexOf(';', num1);
                                          if (num2 > num1)

                                          {
                                                this.m_CharacterSet = text1.Substring(num1, num2).Trim();
                                                break;
                                          }
                                          this.m_CharacterSet = text1.Substring(num1).Trim();
                                          break;
                                    }
                              }
                        }
                  }
            }
            return this.m_CharacterSet;
      }http://m.survivalescaperooms.com/xuanfeng/archive/2007/01/21/626296.html

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 芒康县| 尼勒克县| 镇平县| 大埔县| 大厂| 丽水市| 遂溪县| 马边| 延庆县| 祁门县| 河津市| 岚皋县| 大城县| 延吉市| 金坛市| 邵东县| 江门市| 文登市| 响水县| 横山县| 随州市| 敦化市| 仁寿县| 贵南县| 故城县| 紫云| 台州市| 德兴市| 平罗县| 沽源县| 闵行区| 满城县| 绿春县| 罗甸县| 乡城县| 简阳市| 台东市| 东阳市| 文成县| 涞水县| 同德县|