欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C#教程

當(dāng)前位置:主頁(yè) > 軟件編程 > C#教程 >

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

來源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C#教程|點(diǎn)擊: 次

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

復(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ù)的字符串形式,然后可以對(duì)網(wǎng)頁(yè)進(jìn)行解析了(其實(shí)就是對(duì)字符串的各種操作和正則表達(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("<", "<");
    strOutput = strOutput.Replace(">", ">");
    return strOutput;
}

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

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

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

網(wǎng)頁(yè)制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫(kù)服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有