从网页抓取数据的一般方法
首先要了解对方网页的运行机制 ,这可以用httpwacth或者httplook来看一下http发送和接收的数据。这两个工具应该说是比较简单易懂的。这里就不再介绍了。主要关注的内容是header和post的内容。一般会包括cookie,Referer页面和其他一些乱其八糟可能看不懂的变量,还有就是正常交互的参数,比如需要post或者get的querystring所包含的东西。
httplook和httpwacth 网上有很多下载的,这里推荐使用httpwach,因为可以直接嵌入到ie中,个人觉得这个比较好用。这两个工具可以到我上传在****的资源中下载,地址为
http://download.****.net/user/jinjazz
这里简单给出一段可以抓取数据的c#代码,比如登录某个网站,获取登录成功后的html代码,供数据分析使用。
private
void
login()
{
System.Net.WebClient wb = new System.Net.WebClient();
System.Collections.Specialized.NameValueCollection header = new System.Collections.Specialized.NameValueCollection();
header.Add( " Cookie " , " czJ_cookietime=2592000; czJ_onlineusernum=1651; czJ_sid=w4bGJd " );
header.Add( " Referer " , @" http://www.test_by_jinjazz.com.cn/bbs/login.php " );
wb.Headers.Add(header);
System.Collections.Specialized.NameValueCollection data = new System.Collections.Specialized.NameValueCollection();
data.Add( " formhash " , " ebd2faac " );
data.Add( " referer " , " http://www.test_by_jinjazz.com.cn/bbs/search.php " );
data.Add( " loginfield " , " username " );
data.Add( " username " , " jinjazz " );
data.Add( " password " , " 999 " );
data.Add( " questionid " , " 0 " );
data.Add( " answer " , "" );
data.Add( " cookietime " , " 2592000 " );
data.Add( " loginmode " , "" );
data.Add( " styleid " , "" );
data.Add( " loginsubmit " , " 提交 " );
byte [] b = wb.UploadValues( " http://www.test_by_jinjazz.com.cn/bbs/login.php " , " Post " , data);
string strData = System.Text.Encoding.Default.GetString(b);
Console.WriteLine(strData);
}
{
System.Net.WebClient wb = new System.Net.WebClient();
System.Collections.Specialized.NameValueCollection header = new System.Collections.Specialized.NameValueCollection();
header.Add( " Cookie " , " czJ_cookietime=2592000; czJ_onlineusernum=1651; czJ_sid=w4bGJd " );
header.Add( " Referer " , @" http://www.test_by_jinjazz.com.cn/bbs/login.php " );
wb.Headers.Add(header);
System.Collections.Specialized.NameValueCollection data = new System.Collections.Specialized.NameValueCollection();
data.Add( " formhash " , " ebd2faac " );
data.Add( " referer " , " http://www.test_by_jinjazz.com.cn/bbs/search.php " );
data.Add( " loginfield " , " username " );
data.Add( " username " , " jinjazz " );
data.Add( " password " , " 999 " );
data.Add( " questionid " , " 0 " );
data.Add( " answer " , "" );
data.Add( " cookietime " , " 2592000 " );
data.Add( " loginmode " , "" );
data.Add( " styleid " , "" );
data.Add( " loginsubmit " , " 提交 " );
byte [] b = wb.UploadValues( " http://www.test_by_jinjazz.com.cn/bbs/login.php " , " Post " , data);
string strData = System.Text.Encoding.Default.GetString(b);
Console.WriteLine(strData);
}
以上代码除了三个url之外其他数据都是真实的,其中header和data中的参数和值都是用httpwatch来监测后得到。