HTML数据采集

来源:互联网 发布:1962年印度战争 知乎 编辑:程序博客网 时间:2024/06/16 10:52
============获取html内容
using system.net;
using system.IO;
string url = "http://www.baidu.com";
//实例化WebClinet对象
WebClient myweb = new WebClinet(); 
//根据指定的url获取流
Stream stream = myweb.OpenRead(url); 
//从流中用utf8编码实例化一个读取器
StreamReader sr = new StreamReader(stream,Encoding.utf8);
//从流中读取数据得到字符串
string html = sr.ReadToEnd(); 


==============使用正则提取特定内容
using system.Text.RegularExpressions;
//引号里面填写正则表达式
Regex r = new Regex(""); 
//匹配所有项返回一个集合
MatchCollection co = r.Matches(html);  
//通过下标获取值
co[0].value 


=============获取列表页链接


string url ="http://www.baidu.com/list.html";
string listhtml =gethtml(listurl,Encoding.Default);
//引号里填写正则
Regex rlist = new Regex("");
//匹配所有项返回一个集合
MatchCollection co = rlist.Matches(listhtml);
遍历这个集合
for (int i = 0; i< co.Count; i++)
{
if(co[i].Value.ToString().Contains("article")
{
co[i].Value;
}
}




public static string gethtml(string url,Encoding enc){
WebClient myweb = new WebClinet(); 
//根据指定的url获取流
Stream stream = myweb.OpenRead(url); 
//从流中用utf8编码实例化一个读取器
StreamReader sr = new StreamReaderstream,enc);
//从流中读取数据得到字符串
string html = sr.ReadToEnd(); 
return(html);
}


====================================================================
文件夹操作  文件操作


string [] drivers = Directory.GetLogicalDrives();//获取本地驱动器列表


Directory.GetCurrentDirectory() //获取当前应用程序的运行目录


string [] files = directory.GetFiles("C:\\") //获取指定目录下面的所有文件列表,返回数组
foreach(string s in files)
{
Console.WriteLine(s);
}


DirectoryInfo din = new DiretoryInfo("c:\\1111");
Console.WriteLine(din.Exists); //判断一个目录是否存在
if(!din.Exists){
din.Create(); //创建文件夹
}
din.Delete(true); //删除目录和它里面的子目录和文件


File.AppendAllText("c://1.txt","\r\n文件不存在自动创建,内容自动追加" );


File.WriteAllLines("c://1.txt",files);


File.WriteAllText("c://1.txt","wwwwwwwwwwwwww");


File.Delete("c://1.txt");


 
0 0
原创粉丝点击