欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net(c#)做一个网页数据采集工具

程序员文章站 2024-03-09 10:38:35
通过这个软件一两天就完成了几千产品数据的录入,可见很多工作不是一味用人工去做,作为一个程序员,就是要让很多让那些经常做重复性的、繁琐的工作中的人解放出来。下面只是写了一些核...
通过这个软件一两天就完成了几千产品数据的录入,可见很多工作不是一味用人工去做,作为一个程序员,就是要让很多让那些经常做重复性的、繁琐的工作中的人解放出来。下面只是写了一些核心代码,而且采集必须要和对应网站相挂钩,作者:郑少群

复制代码 代码如下:

//提取产品列表页中产品最终页的网页
private void button1_click(object sender, eventargs e)
{
if (textbox1.text.trim() == "" || textbox2.text.trim() == "")
{
messagebox.show("网址和域名不能为空!", "信息提示", messageboxbuttons.ok, messageboxicon.information);
return;
}
try
{
string html = inc.gethtml("http://study.pctoday.net.cn");
//arraylist al = inc.getmatchesstr(html, "<a[^>]*?>.*?</a>");
arraylist al = inc.getmatchesstr(html, @"href\s*=\s*(?:[\'\""\s](?<1>[^\""\']*)[\'\""])");//提取链接


" title="replica watches:">replica watches buy full quality popular luxury watches at amazing price, your one stop discount swiss watches storeexclusive replica rolex watches, tag heuer watches replica, cartier watches online sale!
stringbuilder sb = new stringbuilder();
foreach (object var in al)
{
string a = var.tostring().replace("\"", "").replace("'", "");
a = regex.replace(a, "href=", "", regexoptions.ignorecase | regexoptions.multiline);
if (a.startswith("/"))
a = textbox2.text.trim() + a;
if (!a.startswith("http://"))
a = "http://" + a;
sb.append(a + "\r\n");
}
textbox5.text = sb.tostring();//把提取到网址输出到一个textbox,每个链接占一行



messagebox.show("共提取" + al.count.tostring() + "个链接", "信息提示", messageboxbuttons.ok, messageboxicon.information);

}
catch (exception err)
{
messagebox.show("提取出错!原因:" + err.message, "信息提示", messageboxbuttons.ok, messageboxicon.information);
}

}




//把采集的产品页面html代码进行字符串处理,提取需要的代码,最后保存到本地一个access数据库中,同时提取产品图片地址并自动现在图片到本地images文件夹下

private void backgroundworker1_dowork(object sender, doworkeventargs e)
{
//填充产品表
database.executenonquery("delete from tb_product");
datatable dt2 = new datatable();
oledbconnection conn = new oledbconnection(database.connectionstrings);
oledbdataadapter da = new oledbdataadapter("select * from tb_product", conn);
oledbcommandbuilder cb = new oledbcommandbuilder(da);
da.fill(dt2);
dt2.rows.clear();

backgroundworker worker = (backgroundworker)sender;//这个是做一个进度条

string[] urls = textbox5.text.trim().tolower().replace("\r\n", ",").split(',');
datatable dt = new datatable();
stringbuilder errorstr = new stringbuilder();
string html = "", imagedir = appdomain.currentdomain.basedirectory + "images\\";

//循环每次采集网址
for (int i = 0; i < urls.length; i++)
{
try
{
if (!worker.cancellationpending)
{
if (urls[i] == "")
return;
html = inc.gethtml(urls[i]);//获取该url的html代码
datarow newrow = dt2.newrow();

//产品名
string productname = html.substring(html.indexof("<title>") + 7);
newrow["productname"] = productname.remove(productname.indexof("</title>")).trim();

//产品编号
newrow["modelid"] = newrow["productname"].tostring().substring(newrow["productname"].tostring().indexof("model:") + 6).trim();

//产品介绍,这些都是根据不同网站的html做相应的修改
string introduce = html.substring(html.indexof("product details") + 26);
introduce = introduce.remove(introduce.indexof("</table>") + 8).trim()

newrow["introduce"] = introduce;



" title="replica watches:">replica watches buy full quality popular luxury watches at amazing price, your one stop discount swiss watches storeexclusive replica rolex watches, tag heuer watches replica, cartier watches online sale!
//下载图片
string productimage = html.substring(html.indexof("align=center><img") + 17);
productimage = textbox2.text.trim() + productimage.substring(productimage.indexof("src=\"") + 5);
productimage = productimage.remove(productimage.indexof("\""));
try
{
inc.downfile(productimage, imagedir + productimage.substring(productimage.lastindexof("/") + 1));
}
catch (exception)
{
errorstr.append("下载图片失败,图片地址:" + imagedir + productimage.substring(productimage.lastindexof("/") + 1) + "\r\n");
}


dt2.rows.add(newrow);

//thread.sleep(100);
worker.reportprogress((i + 1) * 100 / urls.length, i);
toolstripstatuslabel1.text = "处理进度:" + (i + 1).tostring() + "/" + urls.length.tostring();//进度条
}

}
catch (exception err)
{
errorstr.append("采集错误:" + err.message + ";网址:" + urls[i] + "\r\n");
}
}
da.update(dt2);
databind(dt2);
showerror(errorstr.tostring());
}

/// <summary>
/// aspx页面生成静态html页面,作者:郑少群
/// </summary>
public static string gethtml(string url)
{
streamreader sr = null;
string str = null;
//读取远程路径
webrequest request = webrequest.create(url);
httpwebresponse response = (httpwebresponse)request.getresponse();
sr = new streamreader(response.getresponsestream(), encoding.getencoding(response.characterset));
str = sr.readtoend();
sr.close();
return str;
}


// 提取html代码中的网址
public static arraylist getmatchesstr(string htmlcode, string strregex)
{
arraylist al = new arraylist();

regex r = new regex(strregex, regexoptions.ignorecase | regexoptions.multiline);
matchcollection m = r.matches(htmlcode);

for (int i = 0; i < m.count; i++)
{
bool rep = false;
string strnew = m[i].tostring();

// 过滤重复的url
foreach (string str in al)
{
if (strnew == str)
{
rep = true;
break;
}
}

if (!rep) al.add(strnew);
}

al.sort();

return al;
}

public static void downfile(string url, string path)
{

httpwebrequest request = (httpwebrequest)webrequest.create(url);
httpwebresponse response = (httpwebresponse)request.getresponse();
stream stream = response.getresponsestream();
long size = response.contentlength;
//创建文件流对象
using (filestream fs = new filestream(path, filemode.openorcreate, fileaccess.write))
{
byte[] b = new byte[1025];
int n = 0;
while ((n = stream.read(b, 0, 1024)) > 0)
{
fs.write(b, 0, n);
}
}
}