C#获取网页内容,并且处理正确编码
控制台调用
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#获取网页内容,并且处理正确编码的更多相关文章
- C#获取网页内容 (WebClient、WebBrowser和HttpWebRequest/HttpWebResponse)
获取网页数据有很多种方式.在这里主要讲述通过WebClient.WebBrowser和HttpWebRequest/HttpWebResponse三种方式获取网页内容. 这里获取的是包括网页的所有信息 ...
- C#获取网页内容的三种方式
C#通常有三种方法获取网页内容,使用WebClient.WebBrowser或者HttpWebRequest/HttpWebResponse... 方法一:使用WebClient (引用自:http: ...
- 基于apache —HttpClient的小爬虫获取网页内容
今天(17-03-31)忙了一下午研究webmagic,发现自己还太年轻,对于这样难度的框架(类库) 还是难以接受,还是从基础开始吧,因为相对基础的东西教程相多一些,于是乎我找了apache其下的 H ...
- C#获取网页内容的三种方式(转)
搜索网络,发现C#通常有三种方法获取网页内容,使用WebClient.WebBrowser或者HttpWebRequest/HttpWebResponse... 方法一:使用WebClient (引用 ...
- 【C#】获取网页内容及HTML解析器HtmlAgilityPack的使用
最近经常需要下载一些东西,而这个下载地址又会经过层层跳转,每个页面上都有很多广告,烦不胜烦,所以做了一个一键获得最终下载地址的小工具.使用C#,来获取网页内容,然后通过HtmlAgilityPack获 ...
- JS获取url参数及url编码、解码
完整的URL由这几个部分构成:scheme://host:port/path?query#fragment ,各部分的取法如下: window.location.href:获取完整url的方法:,即s ...
- 定义一个方法get_page(url),url参数是需要获取网页内容的网址,返回网页的内容。提示(可以了解python的urllib模块)
定义一个方法get_page(url),url参数是需要获取网页内容的网址,返回网页的内容.提示(可以了解python的urllib模块) import urllib.request def get_ ...
- 使用Jsoup获取网页内容超时设置
使用Jsoup获取网页内容超时设置 最近使用Jsoup来抓取网页,并对网页进行解析,发现很好用.在抓取过程中遇到一个问题,有些页面总是报Timeout异常,开始想是不是被抓取网站对IP进行了限制,后来 ...
- 使用selenium和phantomJS浏览器获取网页内容的小演示
# 使用selenium和phantomJS浏览器获取网页内容的小演示 # 导入包 from selenium import webdriver # 使用selenium库里的webdriver方法调 ...
- [PHP学习教程 - 网络]002.获取网页内容(URL Content)
引言:获取网页内容是我们实现网页操作的基本之基本,今天这一讲,我们和大家讲一下基本请求网页内容的几种方法. 我们似乎每天都要做这样一件事情,打开一个浏览器,输入网址,回车,一个空白的页面顿时有了东西, ...
随机推荐
- linux中shell,awk,sed截取字符串方法总结
转自:http://www.cnblogs.com/kinga/p/5772566.html Shell 第一种: ${parameter%word} 最小限度从后面截掉word${parameter ...
- HDU 1028 HDU 1398 (母函数)
题意:输入一个n 给出其所有组合数 如: 4 = 4; 4 = 3 + 1; 4 = 2 + 2; 4 = 2 + 1 + 1; 4 = 1 + 1 + 1 + 1; 重复不算 母函数入门题 ...
- ICMP隧道工具ptunnel
ICMP隧道工具ptunnel 在一些网络环境中,如果不经过认证,TCP和UDP数据包都会被拦截.如果用户可以ping通远程计算机,就可以尝试建立ICMP隧道,将TCP数据通过该隧道发送,实现不受 ...
- 1003 Emergency (25)(25 point(s))
problem 1003 Emergency (25)(25 point(s)) As an emergency rescue team leader of a city, you are given ...
- [Luogu5161]WD与数列(后缀数组/后缀自动机+线段树合并)
https://blog.csdn.net/WAautomaton/article/details/85057257 解法一:后缀数组 显然将原数组差分后答案就是所有不相交不相邻重复子串个数+n*(n ...
- [POI2017]Sabotaż
[POI2017]Sabotaż 题目大意: 一棵\(n(n\le5\times10^5)\)个结点的树,初始时有一个未知的黑点,其余全为白点.对于一个点,如果其子树中黑点所占比例超过\(x\),则这 ...
- vijos p1882 智力题
题意: 清晨, Alice与Bob在石阶上玩砖块.他们每人都有属于自己的一堆砖块.每人的砖块都由N列组成且N是奇数.Alice的第i列砖块有m[i]个.而Bob的第i列砖块有s[i]个. 他们想建造城 ...
- ROS知识(14)----局部避障的动态窗口算法(DWA)及其调试的方法
Dynamic Window Approach(DWA)是重要的局部轨迹规划算法,ROS中使用了DWA算法获得了很好的局部路径规划的效果.具体的教程可参考官方的导航调试资料Navigation Tun ...
- CGI 、PHP-CGI、FASTCGI、PHP-FPM
CGI是干嘛的? CGI是为了保证web server传递过来的数据是标准格式的,方便CGI程序的编写者.web server(比如说nginx)只是内容的分发者.比如,如果请求的是/index/ht ...
- 磁盘满了MySQL会做什么?
最近遇到一个故障和磁盘满有关系,并且同事也发现经常有磁盘满导致操作hang住无响应的情况,于是抽时间研究了一下这2种情况. 一.磁盘满了之后MySQL会做什么? 我们看下官方的说法 When a di ...