日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

C#抓取网页HTML内容

發(fā)布時間:2023/12/10 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C#抓取网页HTML内容 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Net;

using System.Text;

using System.IO;

using System.Text.RegularExpressions;


namespace Web

{

? ?/// <summary>??

? ?/// 公共方法類??

? ?/// </summary>??

? ?public class WebHandler

? ?{

? ? ? /// <summary>??

? ? ? /// 獲取網(wǎng)頁的HTML碼??

? ? ? /// </summary>??

? ? ? /// <param name="url">鏈接地址</param>??

? ? ? /// <param name="encoding">編碼類型</param>??

? ? ? /// <returns></returns>??

? ? ? public static string GetHtmlStr(string url, string encoding)

? ? ? {

? ? ? ? ?string htmlStr = "";

? ? ? ? ?try

? ? ? ? ?{

? ? ? ? ? ? if (!String.IsNullOrEmpty(url))

? ? ? ? ? ? {

? ? ? ? ? ? ? ?WebRequest request = WebRequest.Create(url);? ? ? ? ? ? //實例化WebRequest對象??

? ? ? ? ? ? ? ?WebResponse response = request.GetResponse();? ? ? ? ? ?//創(chuàng)建WebResponse對象??

? ? ? ? ? ? ? ?Stream datastream = response.GetResponseStream();? ? ? ?//創(chuàng)建流對象??

? ? ? ? ? ? ? ?Encoding ec = Encoding.Default;

? ? ? ? ? ? ? ?if (encoding == "UTF8")

? ? ? ? ? ? ? ?{

? ? ? ? ? ? ? ? ? ec = Encoding.UTF8;

? ? ? ? ? ? ? ?}

? ? ? ? ? ? ? ?else if (encoding == "Default")

? ? ? ? ? ? ? ?{

? ? ? ? ? ? ? ? ? ec = Encoding.Default;

? ? ? ? ? ? ? ?}

? ? ? ? ? ? ? ?StreamReader reader = new StreamReader(datastream, ec);

? ? ? ? ? ? ? ?htmlStr = reader.ReadToEnd();? ? ? ? ? ? ? ? ? //讀取網(wǎng)頁內(nèi)容??

? ? ? ? ? ? ? ?reader.Close();

? ? ? ? ? ? ? ?datastream.Close();

? ? ? ? ? ? ? ?response.Close();

? ? ? ? ? ? }

? ? ? ? ?}

? ? ? ? ?catch { }

? ? ? ? ?return htmlStr;

? ? ? }

? ?}??

? ?

}


總結(jié)

以上是生活随笔為你收集整理的C#抓取网页HTML内容的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。