您的位置:首页 > 编程语言 > C#

c#(winform)抓取网页源码和链接

2013-05-21 08:46 417 查看
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace pachong
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
HttpWebRequest request;   //HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据

HttpWebResponse response;   //这两个类位 于System.Net命名空间,默认情况下这个类对于控制台程序来说是可访问的。

TextReader tr;    //Text的读取器

string url = textBox1.Text.ToString();
request = (HttpWebRequest)WebRequest.Create(url);  //为指定的url方案初始化新的实例

response = (HttpWebResponse)request.GetResponse();  //返回来自internet资源的响应

tr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(936));

textBox2.Text = tr.ReadToEnd();
response.Close();
WebExpress(textBox2.Text.ToString());
}
private void WebExpress(string s)
{
string tag1 = "<a href=";
string tag2 = ">";
/*IndexOf()方法搜索在该字符串上是否出现了作为参数传递的字符串,
* 如果找到字符串,则返回字符的起始位置
* (0表示第一个字符,1表示第二个字符依此类推)如果说没有找到则返回 -1*/

int pos3, pos2, pos1 = s.IndexOf(tag1);  //指定字符串在实例中的第一个匹配串的索引

while (pos1 > 0)
{
pos2 = s.IndexOf(tag2, pos1 + 1);
if (pos2 < 0)
return;
pos3 = s.IndexOf(" ", pos1 + 5);
if (pos3 > 0 && pos3 < pos2)
pos2 = pos3;
string url = s.Substring(pos1 + tag1.Length, pos2 - pos1 - tag1.Length);
url = url.Replace("\"", "");
if (url.IndexOf("http") >= 0)
textBox3.Text += url + "\n";
else url = url + "http://nbubs.nbu.edu.cn";
textBox3.Text += url + "\n";
s = s.Substring(pos2 + 1);
pos1 = s.IndexOf(tag1);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: