欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#抓取網(wǎng)頁數(shù)據(jù) 解析標(biāo)題描述圖片等信息 去除HTML標(biāo)簽

 更新時間:2016年04月19日 11:17:28   作者:seeyou  
本文主要一步一步介紹利用C#抓取頁面數(shù)據(jù)的過程,抓取HTML,獲取標(biāo)題、描述、圖片等信息,并去除HTML,希望對大家有所幫助。

一、首先將網(wǎng)頁內(nèi)容整個抓取下來,數(shù)據(jù)放在byte[]中(網(wǎng)絡(luò)上傳輸時形式是byte),進(jìn)一步轉(zhuǎn)化為String,以便于對其操作,實例如下:

復(fù)制代碼 代碼如下:

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)題

復(fù)制代碼 代碼如下:

Match TitleMatch = Regex.Match(strResponse, "<title>([^<]*)</title>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
title = TitleMatch.Groups[1].Value;

2.獲取描述信息

復(fù)制代碼 代碼如下:

Match Desc = Regex.Match(strResponse, "<meta name=\"DESCRIPTION\" content=\"([^<]*)\">", RegexOptions.IgnoreCase | RegexOptions.Multiline);
strdesc = Desc.Groups[1].Value;

3.獲取圖片

復(fù)制代碼 代碼如下:

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)簽

復(fù)制代碼 代碼如下:

private string StripHtml(string strHtml)
{
    Regex objRegExp = new Regex("<(.|\n)+?>");
    string strOutput = objRegExp.Replace(strHtml, "");
    strOutput = strOutput.Replace("<", "&lt;");
    strOutput = strOutput.Replace(">", "&gt;");
    return strOutput;
}

有些例外會使得去除不干凈,所以建議連續(xù)兩次轉(zhuǎn)化。這樣將Html標(biāo)簽轉(zhuǎn)化為了空格。太多連續(xù)的空格會影響之后對字符串的操作。所以再加入這樣的語句:

復(fù)制代碼 代碼如下:

//把所有空格變?yōu)橐粋€空格
Regex r = new Regex(@"\s+");
wordsOnly = r.Replace(strResponse, " ");
wordsOnly.Trim();

相關(guān)文章

最新評論