asp.net 利用HttpWebRequest自动获取网页编码并获取网页源代码

2024-03-17 13:18

本文主要是介绍asp.net 利用HttpWebRequest自动获取网页编码并获取网页源代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

     /// <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 = 20000;request.AllowAutoRedirect = false;response = (HttpWebResponse)request.GetResponse();if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 1024){if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), encoding);elsereader = 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 GetEncoding(string url){HttpWebRequest request = null;HttpWebResponse response = null;StreamReader reader = null;try{request = (HttpWebRequest)WebRequest.Create(url);request.Timeout = 20000;request.AllowAutoRedirect = false;response = (HttpWebResponse)request.GetResponse();if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 1024){if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));elsereader = new StreamReader(response.GetResponseStream(), Encoding.ASCII);string html = reader.ReadToEnd();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;}elsereturn Encoding.Default.BodyName;}}catch{}finally{if (response != null){response.Close();response = null;}if (reader != null)reader.Close();if (request != null)request = null;}}



下面是获取网页标题的

 using System; using System.Net; using System.Text; using System.Text.RegularExpressions; class Program { // 获取网页的HTML内容,根据网页的charset自动判断Encoding static string GetHtml(string url) { return GetHtml(url, null); } // 获取网页的HTML内容,指定Encoding static string GetHtml(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)); } // 程序入口 static void Main() { PrintEncodingAndTitle("http://www.msdn.net/"); PrintEncodingAndTitle("http://www.cnblogs.com/"); PrintEncodingAndTitle("http://www.cnblogs.com/skyiv/"); PrintEncodingAndTitle("http://www.csdn.net/"); PrintEncodingAndTitle("http://news.163.com/"); } } /* 程序输出: [] [MSDN: Microsoft Developer Network] [System.Text.UTF8Encoding] [博客园 - 程序员的网上家园] [System.Text.UTF8Encoding] [空间/IV - 博客园] [System.Text.UTF8Encoding] [CSDN.NET - 中国最大的IT技术社区,为IT专业技术人员提供最全面的信息传播和服务平台] [System.Text.DBCSCodePageEncoding] [新闻中心_网易新闻] */




这篇关于asp.net 利用HttpWebRequest自动获取网页编码并获取网页源代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/819072

相关文章

浏览器插件cursor实现自动注册、续杯的详细过程

《浏览器插件cursor实现自动注册、续杯的详细过程》Cursor简易注册助手脚本通过自动化邮箱填写和验证码获取流程,大大简化了Cursor的注册过程,它不仅提高了注册效率,还通过友好的用户界面和详细... 目录前言功能概述使用方法安装脚本使用流程邮箱输入页面验证码页面实战演示技术实现核心功能实现1. 随机

MySQL 获取字符串长度及注意事项

《MySQL获取字符串长度及注意事项》本文通过实例代码给大家介绍MySQL获取字符串长度及注意事项,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录mysql 获取字符串长度详解 核心长度函数对比⚠️ 六大关键注意事项1. 字符编码决定字节长度2

解决未解析的依赖项:‘net.sf.json-lib:json-lib:jar:2.4‘问题

《解决未解析的依赖项:‘net.sf.json-lib:json-lib:jar:2.4‘问题》:本文主要介绍解决未解析的依赖项:‘net.sf.json-lib:json-lib:jar:2.4... 目录未解析的依赖项:‘net.sf.json-lib:json-lib:jar:2.4‘打开pom.XM

python3如何找到字典的下标index、获取list中指定元素的位置索引

《python3如何找到字典的下标index、获取list中指定元素的位置索引》:本文主要介绍python3如何找到字典的下标index、获取list中指定元素的位置索引问题,具有很好的参考价值,... 目录enumerate()找到字典的下标 index获取list中指定元素的位置索引总结enumerat

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

一文详解MySQL如何设置自动备份任务

《一文详解MySQL如何设置自动备份任务》设置自动备份任务可以确保你的数据库定期备份,防止数据丢失,下面我们就来详细介绍一下如何使用Bash脚本和Cron任务在Linux系统上设置MySQL数据库的自... 目录1. 编写备份脚本1.1 创建并编辑备份脚本1.2 给予脚本执行权限2. 设置 Cron 任务2

C++中RAII资源获取即初始化

《C++中RAII资源获取即初始化》RAII通过构造/析构自动管理资源生命周期,确保安全释放,本文就来介绍一下C++中的RAII技术及其应用,具有一定的参考价值,感兴趣的可以了解一下... 目录一、核心原理与机制二、标准库中的RAII实现三、自定义RAII类设计原则四、常见应用场景1. 内存管理2. 文件操