C#网页数据采集(三)HttpWebRequest
2024-09-06 05:06:55
- <span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">截取到网页数据是js加载完以后的</span>
- <span style="white-space:pre"> </span> HtmlWeb webClient = new HtmlWeb();
- string _url = "http://news.baidu.com/";
- HtmlAgilityPack.HtmlDocument html1 = webClient.Load(_url);//是你需要解析的url
- var end3 = html1.Encoding.BodyName;//获取页面编码格式
- string _htmlSource = GetHtmlSource(_url, System.Text.Encoding.GetEncoding(end3));//还是需要设置一次编码格式避免乱码 调用<span style="font-family: Arial, Helvetica, sans-serif;">GetHtmlSource方法</span>
- public static string GetHtmlSource(string url, Encoding charset)
- {
- string _html = string.Empty;
- try
- {
- HttpWebRequest _request = (HttpWebRequest)WebRequest.Create(url);
- HttpWebResponse _response = (HttpWebResponse)_request.GetResponse();
- using (Stream _stream = _response.GetResponseStream())
- {
- using (StreamReader _reader = new StreamReader(_stream, charset))
- {
- _html = _reader.ReadToEnd();
- }
- }
- }
- catch (WebException ex)
- {
- using (StreamReader sr = new StreamReader(ex.Response.GetResponseStream()))
- {
- _html = sr.ReadToEnd();
- }
- }
- catch (Exception ex)
- {
- _html = ex.Message;
- }
- return _html;
- }
最新文章
- JavaScript填坑史
- Linux head和tail命令
- phalcon: 获取参数的方法
- fil_space_t
- js实现图片上传及预览---------------------->;>;兼容ie6-8 火狐以及谷歌
- linux内核交互,设备驱动控制管理接口
- 在Windows环境下部署Axis2/C服务
- Android开源项目(一)
- c语言数组应用--统计随机数并打印直方图
- springboot学习笔记-1 第一个springboot示例
- Screen tearing
- win7 点IE浏览器无法打开
- 三, 练习 python索引 (list和tuple)
- Koa,React和socket.io
- python爬虫快递查询系统(源码)
- VLC框架分析
- elcipse 安装lombok插件解决 @Slf4j 等找不到log变量问题
- Oracle数据库中的数据出错的解决办法
- [leetcode]122. Best Time to Buy and Sell Stock II 最佳炒股时机之二
- (轉)Equal height boxes with CSS