C#抓取網(wǎng)頁數(shù)據(jù) 解析標(biāo)題描述圖片等信息 去除HTML標(biāo)簽
一、首先將網(wǎng)頁內(nèi)容整個抓取下來,數(shù)據(jù)放在byte[]中(網(wǎng)絡(luò)上傳輸時形式是byte),進(jìn)一步轉(zhuǎn)化為String,以便于對其操作,實例如下:
private static string GetPageData(string url)
{
if (url == null || url.Trim() == "")
return null;
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultCredentials;
Byte[] pageData = wc.DownloadData(url);
return Encoding.Default.GetString(pageData);//.ASCII.GetString
}
二、得到了數(shù)據(jù)的字符串形式,然后可以對網(wǎng)頁進(jìn)行解析了(其實就是對字符串的各種操作和正則表達(dá)式的應(yīng)用):
常用的的解析還有以下幾種:
1.獲取標(biāo)題
Match TitleMatch = Regex.Match(strResponse, "<title>([^<]*)</title>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
title = TitleMatch.Groups[1].Value;
2.獲取描述信息
Match Desc = Regex.Match(strResponse, "<meta name=\"DESCRIPTION\" content=\"([^<]*)\">", RegexOptions.IgnoreCase | RegexOptions.Multiline);
strdesc = Desc.Groups[1].Value;
3.獲取圖片
public class HtmlHelper
{
/// <summary>
/// HTML中提取圖片地址
/// </summary>
public static List<string> PickupImgUrl(string html)
{
Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
MatchCollection matches = regImg.Matches(html);
List<string> lstImg = new List<string>();
foreach (Match match in matches)
{
lstImg.Add(match.Groups["imgUrl"].Value);
}
return lstImg;
}
/// <summary>
/// HTML中提取圖片地址
/// </summary>
public static string PickupImgUrlFirst(string html)
{
List<string> lstImg = PickupImgUrl(html);
return lstImg.Count == 0 ? string.Empty : lstImg[0];
}
}
4.去除Html標(biāo)簽
private string StripHtml(string strHtml)
{
Regex objRegExp = new Regex("<(.|\n)+?>");
string strOutput = objRegExp.Replace(strHtml, "");
strOutput = strOutput.Replace("<", "<");
strOutput = strOutput.Replace(">", ">");
return strOutput;
}
有些例外會使得去除不干凈,所以建議連續(xù)兩次轉(zhuǎn)化。這樣將Html標(biāo)簽轉(zhuǎn)化為了空格。太多連續(xù)的空格會影響之后對字符串的操作。所以再加入這樣的語句:
//把所有空格變?yōu)橐粋€空格
Regex r = new Regex(@"\s+");
wordsOnly = r.Replace(strResponse, " ");
wordsOnly.Trim();
- c#使用htmlagilitypack解析html格式字符串
- C#自寫的一個HTML解析類(類似XElement語法)
- c#使用nsoup解析html亂碼解決方法分享 nsoup教程
- C#下解析HTML的兩種方法介紹
- C# 使用 WebBrowser 實現(xiàn) HTML 轉(zhuǎn)圖片功能的示例代碼
- 利用C#代碼將html樣式文件與Word文檔互換的方法
- C#正則過濾HTML標(biāo)簽并保留指定標(biāo)簽的方法
- C#基于正則表達(dá)式抓取a標(biāo)簽鏈接和innerhtml的方法
- 通過C#實現(xiàn)發(fā)送自定義的html格式郵件
- c# 使用HtmlAgilityPack解析Html
相關(guān)文章
Winform ComboBox如何獨立繪制下拉選項的字體顏色
這篇文章主要介紹了Winform ComboBox如何獨立繪制下拉選項的字體顏色,幫助大家更好的理解和使用c# winform,感興趣的朋友可以了解下2020-11-11C# winform編程中響應(yīng)回車鍵的實現(xiàn)代碼
這篇文章主要介紹了C# winform編程中響應(yīng)回車鍵的實現(xiàn)代碼,既在窗口上響應(yīng)回車鍵事件的方法,需要的朋友可以參考下2014-08-08C# 如何調(diào)用C++ dll string類型返回
這篇文章主要介紹了C# 如何調(diào)用C++ dll string類型返回問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11c#入門之枚舉和結(jié)構(gòu)體使用詳解(控制臺接收字符串以相反的方向輸出)
這篇文章主要介紹了c#入門之枚舉和結(jié)構(gòu)體使用詳解,最后提供了編寫控制臺應(yīng)用程序接收字符串并做相應(yīng)處理的小示例,需要的朋友可以參考下2014-04-04winform模擬鼠標(biāo)按鍵的具體實現(xiàn)
這篇文章介紹了winform模擬鼠標(biāo)按鍵的具體實現(xiàn),有需要的朋友可以參考一下2013-10-10