[原创]把返回的Html代码保存----爬虫程序(二)
上一篇已经把Html代码和编码信息弄到本地了,这时候还是存在内存,你的string字符串中,如果你不想保存,依然可以直接分析这个字符串,然后抛弃它,不备份.如果希望以后还可以使用或参考,想备份下来的话,那一般就可以吧这个string存到某个储存介质中.存到数据库我就不写了,太简单了,一个数据库insert或update操作而已.
写一下如何存进文件吧.这是从string型字符串写入文件,也是基础的代码.重点是写入sw时的编码需要设置,不然读下来gb2312编码的页面,默认写入的话可能就会中文乱码,这个问题只会出现在中文和日文里貌似,如果你只抓取英文页面就不用考虑了.
private bool insertFile(string str, string encodingType)
{
string path = filePathTXT.Text.ToString().Trim() + System.DateTime.Now.ToShortDateString()
+ System.DateTime.Now.Hour.ToString()
+ System.DateTime.Now.Minute + System.DateTime.Now.Second
+ System.DateTime.Now.Millisecond.ToString() + ".html"; StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding(encodingType)); try { sw.Write(str); return true; } catch (Exception ex) { MessageBox.Show(ex.Message); return false; } finally { sw.Close(); } }