这里以获取csdn程序员往期杂志为例子
前台代码:
<div>
<asp:Button ID="Button3" runat="server" Text="csdn程序员往期内容" OnClick="Button3_Click" />
</div>
<div runat="server" id="content">这里用来显示获取到的数据</div>
后台代码:
//获取csdn程序员杂志连接
protected void Button3_Click(object sender, EventArgs e)
{
string url = "http://dingyue.programmer.com.cn/"; //连接
string content = getcontent(url);
Regex reg = new Regex(@"<a href=""([^""]+?)""[^>]+?><img[^>]+?src=""([^""]+?)""");
// Match m = reg.Match(content);//不循环,只取第一个
foreach (Match m in reg.Matches(content))
{
string href = m.Groups[1].Value;
string img = m.Groups[2].Value;
string date = img.Substring(img.LastIndexOf("/") + 1, img.LastIndexOf(".") - img.LastIndexOf("/") - 1);
string address = "<a href='" + href + "' target=_blank>" + date.Substring(0, 4) + "年" + date.Substring(4) + "月</a><br/>";
//Response.Write( Server.HtmlEncode( m.Value));
this.content.InnerHtml += address;
}
}
//根据路径获取整个页面内容
private static string getcontent(string url)
{
HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create(url);
WebResponse resp = myWebRequest.GetResponse();
StreamReader oStreamRd = new StreamReader(resp.GetResponseStream(), Encoding.GetEncoding("GB2312"));
string content = oStreamRd.ReadToEnd();
return content;
}
需要用到的命名空间是:
[csharp]
view plain
copy
- using System.Net;