http://www.sufeinet.com/plugin.php?id=keke_group

苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.7-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 3381|回复: 3

[HttpHelper] 请教实现给定url获取源码文件过程中,有的好用,有的就不成功怎么回事?

[复制链接]
发表于 2015-1-20 20:51:45 | 显示全部楼层 |阅读模式
1金钱
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
class abc
{
    public static string getHtml(string url, string charSet)//url是要访问的网站地址,charSet是目标网页的编码,如果传入的是null或者"",那就自动分析网页的编码
    {

        WebClient myWebClient = new WebClient(); //创建WebClient实例myWebClient

        //获取或设置用于对向 Internet 资源的请求进行身份验证的网络凭据。
        myWebClient.Credentials = CredentialCache.DefaultCredentials;
        byte[] myDataBuffer = myWebClient.DownloadData(url);
        string strWebData = Encoding.Default.GetString(myDataBuffer);
        //string strWebData = Encoding.GetEncoding("gb2312").GetString(myDataBuffer);

        //获取网页字符编码描述信息
        Match charSetMatch = Regex.Match(strWebData, "<meta([^<]*)charset=([^<]*)\"", RegexOptions.IgnoreCase | RegexOptions.Multiline);
        string webCharSet = charSetMatch.Groups[2].Value;
        if (charSet == null || charSet == "")
            charSet = webCharSet;
        Console.WriteLine("The page's charset is {0}, press any key", charSet);

        if (charSet != null && charSet != "" && Encoding.GetEncoding(charSet) != Encoding.Default)
            strWebData = Encoding.GetEncoding(charSet).GetString(myDataBuffer);
        Console.WriteLine(strWebData);
        Console.ReadLine();
        return strWebData;

    }


    static void Main(string[] args)
    {
        string url_s, codestr, strResult;
        //url_s = "http://esf.bengbu.fang.com/";
        url_s = "http://esf.bengbu.fang.com/house-xm2115937976/";

        codestr = getHtml(url_s, "");
        Console.WriteLine(codestr);
        Console.ReadLine();
    }

}


上面是源程序,在vs下能正常编译运行。
有个问题就是当url_s = "http://esf.bengbu.fang.com/"时,正常,
可是当url_s = "http://esf.bengbu.fang.com/house-xm2115937976/"时,输出是乱码怎么回事?

实际上,这两个网页,在浏览器上都能正常显示,浏览器用的编码是gb2312,看源码也是gb2312。
可是用这段代码下载,解码,然后结果就不同了,前一个正常,后一个就是乱码。



1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
发表于 2015-1-20 21:59:26 | 显示全部楼层
用我的Httphelper类,或者是万能框架都能自动识别
回复

使用道具 举报

 楼主| 发表于 2015-1-21 10:33:25 | 显示全部楼层
站长试过了?

我试试,先谢谢啦!
回复

使用道具 举报

 楼主| 发表于 2015-1-22 10:17:24 | 显示全部楼层
确实解决问题了!
非常感谢!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 马上注册

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2024-5-18 01:10

© 2014-2021

快速回复 返回顶部 返回列表