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)
引言:获取网页内容是我们实现网页操作的基本之基本,今天这一讲,我们和大家讲一下基本请求网页内容的几种方法. 我们似乎每天都要做这样一件事情,打开一个浏览器,输入网址,回车,一个空白的页面顿时有了东西, ...
随机推荐
- nodejs 项目,请求返回Invalid Host header问题
今天在linux上安装node,使用node做一个web服务器,在linux上安装各种依赖以后开始运行但是,出现了:Invalid Host header 的样式,在浏览器调试中发现是node返回的错 ...
- django视图函数中 应用装饰器
from django.shortcuts import render, redirect, HttpResponse from .forms import LoginForm, Registrati ...
- NetworkX 使用(三)
官方教程 博客:NetworkX NetworkX 使用(二) Introduction to Graph Analysis with NetworkX %pylab inline import ne ...
- CSUOJ 1011 Counting Pixels
Description Did you know that if you draw a circle that fills the screen on your 1080p high definiti ...
- 装饰模式和Java IO
装饰模式 修饰模式(装饰模式),是面向对象编程领域中,一种动态地往一个类中添加新的行为的设计模式.就功能而言,修饰模式相比生成子类更为灵活,这样可以给某个对象而不是整个类添加一些功能. 装饰模式的UM ...
- Spring的模块组成
Spring的模块组成 1.核心容器:核心容器提供 Spring 框架的基本功能(Spring Core).核心容器的主要组件是 BeanFactory,它是工厂模式的实现. BeanFactory ...
- 【洛谷】2474:[SCOI2008]天平【差分约束系统】
P2474 [SCOI2008]天平 题目背景 2008四川NOI省选 题目描述 你有n个砝码,均为1克,2克或者3克.你并不清楚每个砝码的重量,但你知道其中一些砝码重量的大小关系.你把其中两个砝码A ...
- 使用Layui和Vue实现分页
原理就是利用Layui的分页组件和Vue组件的模板渲染功能. 我下面直接贴代码,比较直观. index.html <!DOCTYPE html> <html> <head ...
- Ajax-验证码
function validateCode(){ var code=document.getElementById("code").value; var spanObj=docum ...
- MySQL Proxy 实现MySQLDB 读写分离
一.简述 MySQL Proxy是一个处于你的client端和MySQL server端之间的简单程序,它可以监测.分析或改变它们的通信.它使用灵活,没有限制,常见的用途包括:负载平衡,故障.查询分析 ...