控制台调用
static void Main(string[] args)
{
string code = GetEncodings("http://www.cnblogs.com");
Encoding pp = Encoding.GetEncoding(code);
string pl = GetHtml("http://www.cnblogs.com", pp);
}

下面的代码不重要,只是可以获取标题或其它内容

// 获取网页的HTML内容,根据网页的charset自动判断Encoding
static string GetHtml(string url)
{
return GetHtmls(url, null);
} // 获取网页的HTML内容,指定Encoding
static string GetHtmls(string url, Encoding encoding)
{
byte[] buf = new WebClient().DownloadData(url);
if (encoding != null) return encoding.GetString(buf);
string html = Encoding.UTF8.GetString(buf);
encoding = GetEncoding(html);
if (encoding == null || encoding == Encoding.UTF8) return html;
return encoding.GetString(buf);
} // 根据网页的HTML内容提取网页的Encoding
static Encoding GetEncoding(string html)
{
string pattern = @"(?i)\bcharset=(? <charset>[-a-zA-Z_0-9]+)";
string charset = Regex.Match(html, pattern).Groups["charset"].Value;
try { return Encoding.GetEncoding(charset); }
catch (ArgumentException) { return null; }
} // 根据网页的HTML内容提取网页的Title
static string GetTitle(string html)
{
string pattern = @"(?si) <title(?:\s+(?:""[^""]*""|'[^']*'|[^""'>])*)?>(? <title>.*?) </title>";
return Regex.Match(html, pattern).Groups["title"].Value.Trim();
} // 打印网页的Encoding和Title
static void PrintEncodingAndTitle(string url)
{
string html = GetHtml(url);
Console.WriteLine("[{0}] [{1}]", GetEncoding(html), GetTitle(html));
}

里面的代码不重要,只是获取其它的内容

/// <summary>
/// 获取源代码
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string GetHtml(string url, Encoding encoding)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
StreamReader reader = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = ;
request.AllowAutoRedirect = false;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < * )
{
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), encoding);
else
reader = new StreamReader(response.GetResponseStream(), encoding);
string html = reader.ReadToEnd();
return html;
}
}
catch
{
}
finally
{
if (response != null)
{
response.Close();
response = null;
}
if (reader != null)
reader.Close();
if (request != null)
request = null;
}
return string.Empty;
} public static string GetEncodings(string url)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
StreamReader reader = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = ;
request.AllowAutoRedirect = false;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < * )
{
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
else
reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII);
string html = reader.ReadToEnd();
string pp = html.Substring(html.IndexOf("charset"),);
int p2 = pp.IndexOf(">");
pp=pp.Substring(,p2);
pp = pp.Replace("\\", "").Replace("\"", "").Replace("charset=","").Replace(">","")..Replace("/","").Replace(" ","");;
string p3 = pp;
return p3;
//Regex reg_charset = new Regex(@"charset\b\s*=\s*(?<charset>[^""]*)");
//if (reg_charset.IsMatch(html))
//{
// return reg_charset.Match(html).Groups["charset"].Value;
//}
//else if (response.CharacterSet != string.Empty)
//{
// return response.CharacterSet;
//}
//else
// return Encoding.Default.BodyName;
////XmlDocument xml = new XmlDocument();
////xml.LoadXml(html);
}
return null; }
catch
{
return null;
}
finally
{
if (response != null)
{
response.Close();
response = null;
}
if (reader != null)
reader.Close();
if (request != null)
request = null;
}
}

这里才是真正的代码,这里一个是获取正确的编码,一个是根据编码解析源码

C#获取网页内容,并且处理正确编码的更多相关文章

  1. C#获取网页内容 (WebClient、WebBrowser和HttpWebRequest/HttpWebResponse)

    获取网页数据有很多种方式.在这里主要讲述通过WebClient.WebBrowser和HttpWebRequest/HttpWebResponse三种方式获取网页内容. 这里获取的是包括网页的所有信息 ...

  2. C#获取网页内容的三种方式

    C#通常有三种方法获取网页内容,使用WebClient.WebBrowser或者HttpWebRequest/HttpWebResponse... 方法一:使用WebClient (引用自:http: ...

  3. 基于apache —HttpClient的小爬虫获取网页内容

    今天(17-03-31)忙了一下午研究webmagic,发现自己还太年轻,对于这样难度的框架(类库) 还是难以接受,还是从基础开始吧,因为相对基础的东西教程相多一些,于是乎我找了apache其下的 H ...

  4. C#获取网页内容的三种方式(转)

    搜索网络,发现C#通常有三种方法获取网页内容,使用WebClient.WebBrowser或者HttpWebRequest/HttpWebResponse... 方法一:使用WebClient (引用 ...

  5. 【C#】获取网页内容及HTML解析器HtmlAgilityPack的使用

    最近经常需要下载一些东西,而这个下载地址又会经过层层跳转,每个页面上都有很多广告,烦不胜烦,所以做了一个一键获得最终下载地址的小工具.使用C#,来获取网页内容,然后通过HtmlAgilityPack获 ...

  6. JS获取url参数及url编码、解码

    完整的URL由这几个部分构成:scheme://host:port/path?query#fragment ,各部分的取法如下: window.location.href:获取完整url的方法:,即s ...

  7. 定义一个方法get_page(url),url参数是需要获取网页内容的网址,返回网页的内容。提示(可以了解python的urllib模块)

    定义一个方法get_page(url),url参数是需要获取网页内容的网址,返回网页的内容.提示(可以了解python的urllib模块) import urllib.request def get_ ...

  8. 使用Jsoup获取网页内容超时设置

    使用Jsoup获取网页内容超时设置 最近使用Jsoup来抓取网页,并对网页进行解析,发现很好用.在抓取过程中遇到一个问题,有些页面总是报Timeout异常,开始想是不是被抓取网站对IP进行了限制,后来 ...

  9. 使用selenium和phantomJS浏览器获取网页内容的小演示

    # 使用selenium和phantomJS浏览器获取网页内容的小演示 # 导入包 from selenium import webdriver # 使用selenium库里的webdriver方法调 ...

  10. [PHP学习教程 - 网络]002.获取网页内容(URL Content)

    引言:获取网页内容是我们实现网页操作的基本之基本,今天这一讲,我们和大家讲一下基本请求网页内容的几种方法. 我们似乎每天都要做这样一件事情,打开一个浏览器,输入网址,回车,一个空白的页面顿时有了东西, ...

随机推荐

  1. 解决loadrunner 脚本和replaylog中的中文乱码问题

    解决loadrunner 脚本和replaylog中的中文乱码问题 解决这个问题必须认识到一个事实就是,loadrunner和测试服务器交换数据使用的是utf8格式,但是展现在replaylog中是使 ...

  2. linux下根目录扩容

    划分出一个磁盘,并将其格式化   [root@gg ~]# mkfs.ext3 /dev/sdb2    创建一个物理卷 [root@gg ~]# pvcreate /dev/sdb2    [roo ...

  3. Ionic Tabs

    Ionic 默认的 Tabs 模板 ,Android的在上方,IOS的在下方.在www/js/app.js修改配置,添加一个变量,再修改相应属性: .config(function($statePro ...

  4. java把html标签字符转换成普通字符(反转换成html标签)

    package net.jasonjiang.web; import org.junit.Test; import org.springframework.web.util.HtmlUtils; /* ...

  5. thinkphp 5.0如何实现自定义404(异常处理)页面

    404页面是客户端在浏览网页时,由于服务器无法正常提供信息,或是服务器无法回应,且不知道原因所返回的页面.404承载着用户体验与SEO优化的重任.404页面通常为用户访问了网站上不存在或已删除的页面, ...

  6. softmax 杂谈

    在多分类问题中,我们可以使用 softmax 函数,对输出的值归一化为概率值.下面举个例子: import sys sys.path.append("E:/zlab/") from ...

  7. 机器学习之路: 深度学习 tensorflow 神经网络优化算法 学习率的设置

    在神经网络中,广泛的使用反向传播和梯度下降算法调整神经网络中参数的取值. 梯度下降和学习率: 假设用 θ 来表示神经网络中的参数, J(θ) 表示在给定参数下训练数据集上损失函数的大小. 那么整个优化 ...

  8. android handler messageQueue,looper

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha 处理器获取 当前线程中的 循环器对象, 循环器 从 消息队列中 取出 消息, 给 处理器 ...

  9. Java并发(十七):ConcurrentHashMap

    先做总结: 1.HashMap HashTable ConcurrentHashMap HashMap:线程不安全 HashTable:线程安全,每个方法都加了 synchronized 修饰.类似 ...

  10. python开发_tkinter_单选菜单_不可用菜单操作

    在之前的blog中有提到python的tkinter中的菜单操作 python开发_tkinter_窗口控件_自己制作的Python IDEL_博主推荐 python开发_tkinter_窗口控件_自 ...