当前位置: 首页 > 编程日记 > 正文

自己用C#写一个采集器、蜘蛛(zz)

效果图:

C# 采集器 蜘蛛

代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;


namespace chinaz
{
    
class Program
    {
        
static void Main(string[] args)
        {

            
string cookie = null;
            
using (StreamReader sr = new StreamReader("cookie.txt"))
            {
                cookie 
= sr.ReadToEnd();
                sr.Close();
            }
            
//string tmp = SRWebClient.GetPage("http://bbs.chinaz.com/Members.html?page=1&sort=CreateDate&desc=true&keyword=", Encoding.UTF8, cookie);
            int a = int.Parse(Console.ReadLine());
            
int b = int.Parse(Console.ReadLine());
            
string url = Console.ReadLine();

            Hashtable hash 
= new Hashtable();
            Encoding encoding 
= Encoding.GetEncoding(Console.ReadLine());

            
for (int i = a; i <= b; i++)
            {
                
string html = SRWebClient.GetPage(string.Format(url, i), encoding, cookie);
                
//Console.WriteLine(html);
                if (html != null && html.Length > 1000)
                {
                    Match m 
= Regex.Match(html, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    
while (m != null && m.Value != null && m.Value.Trim() != string.Empty)
                    {
                        
if (!hash.Contains(m.Value))
                        {
                            Console.WriteLine(m.Value);
                            
using (StreamWriter sw = new StreamWriter("mail.txt"true))
                            {
                                sw.WriteLine(m.Value);
                                sw.Close();
                            }
                            hash.Add(m.Value, 
string.Empty);
                        }
                        m 
= m.NextMatch();
                    }

                }
            }



            Console.Write(
"完成");
            Console.ReadLine();
        }
    }


    
public class SRWebClient
    {
        
public CookieCollection cookie;
        
public SRWebClient()
        {
            cookie 
= null;
        }

        
#region 从包含多个 Cookie 的字符串读取到 CookieCollection 集合中
        
private static void AddCookieWithCookieHead(ref CookieCollection cookieCol, string cookieHead, string defaultDomain)
        {
            
if (cookieCol == null) cookieCol = new CookieCollection();
            
if (cookieHead == nullreturn;
            
string[] ary = cookieHead.Split(';');
            
for (int i = 0; i < ary.Length; i++)
            {
                Cookie ck 
= GetCookieFromString(ary[i].Trim(), defaultDomain);
                
if (ck != null)
                {
                    cookieCol.Add(ck);
                }
            }
        }
        
#endregion

        
#region 读取某一个 Cookie 字符串到 Cookie 变量中
        
private static Cookie GetCookieFromString(string cookieString, string defaultDomain)
        {
            
string[] ary = cookieString.Split(',');
            Hashtable hs 
= new Hashtable();
            
for (int i = 0; i < ary.Length; i++)
            {
                
string s = ary[i].Trim();
                
int index = s.IndexOf("=");
                
if (index > 0)
                {
                    hs.Add(s.Substring(
0, index), s.Substring(index + 1));
                }
            }
            Cookie ck 
= new Cookie();
            
foreach (object Key in hs.Keys)
            {
                
if (Key.ToString() == "path") ck.Path = hs[Key].ToString();

                
else if (Key.ToString() == "expires")
                {
                    
//ck.Expires=DateTime.Parse(hs[Key].ToString();
                }
                
else if (Key.ToString() == "domain") ck.Domain = hs[Key].ToString();
                
else
                {
                    ck.Name 
= Key.ToString();
                    ck.Value 
= hs[Key].ToString();
                }
            }
            
if (ck.Name == ""return null;
            
if (ck.Domain == "") ck.Domain = defaultDomain;
            
return ck;
        }
        
#endregion



        
/**/
        
/// <TgData>
        
///     <Alias>下载Web源代码</Alias>
        
/// </TgData>
        public string DownloadHtml(string URL, bool CreateCookie)
        {
            
try
            {
                HttpWebRequest request 
= HttpWebRequest.Create(URL) as HttpWebRequest;
                
if (cookie != null)
                {
                    request.CookieContainer 
= new CookieContainer();
                    request.CookieContainer.Add(cookie);
                }
                request.AllowAutoRedirect 
= false;
                
//request.MaximumAutomaticRedirections = 3;
                request.Timeout = 20000;

                HttpWebResponse res 
= (HttpWebResponse)request.GetResponse();
                
string r = "";

                System.IO.StreamReader S1 
= new System.IO.StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
                
try
                {
                    r 
= S1.ReadToEnd();
                    
if (CreateCookie)
                        cookie 
= res.Cookies;
                }
                
catch (Exception er)
                {
                    
//Log l = new Log();
                    
//l.writelog("下载Web错误", er.ToString());
                }
                
finally
                {
                    res.Close();
                    S1.Close();
                }

                
return r;
            }

            
catch
            {

            }

            
return string.Empty;
        }

        
/**/
        
/// <TgData>
        
///     <Alias>下载文件</Alias>
        
/// </TgData>
        public long DownloadFile(string FileURL, string FileSavePath, bool CreateCookie)
        {
            
long Filelength = 0;
            HttpWebRequest req 
= HttpWebRequest.Create(FileURL) as HttpWebRequest;

            
if (cookie != null)
            {
                req.CookieContainer 
= new CookieContainer();
                req.CookieContainer.Add(cookie);
            }
            req.AllowAutoRedirect 
= true;

            HttpWebResponse res 
= req.GetResponse() as HttpWebResponse;
            
if (CreateCookie)
                cookie 
= res.Cookies;
            System.IO.Stream stream 
= res.GetResponseStream();
            
try
            {
                Filelength 
= res.ContentLength;

                
byte[] b = new byte[512];

                
int nReadSize = 0;
                nReadSize 
= stream.Read(b, 0512);

                System.IO.FileStream fs 
= System.IO.File.Create(FileSavePath);
                
try
                {
                    
while (nReadSize > 0)
                    {
                        fs.Write(b, 
0, nReadSize);
                        nReadSize 
= stream.Read(b, 0512);
                    }
                }
                
finally
                {
                    fs.Close();
                }
            }
            
catch (Exception er)
            {
                
//Log l = new Log();
                
//l.writelog("下载文件错误", er.ToString());
            }
            
finally
            {
                res.Close();
                stream.Close();
            }

            
return Filelength;
        }

        
/**/
        
/// <TgData>
        
///     <Alias>提交数据</Alias>
        
/// </TgData>
        public string Request(string RequestPageURL, RequestData Data, bool CreateCookie)
        {
            StreamReader reader 
= null;
            HttpWebResponse response 
= null;
            HttpWebRequest request 
= null;
            
try
            {
                
string StrUrl = RequestPageURL;
                request 
= HttpWebRequest.Create(StrUrl) as HttpWebRequest;

                
string postdata = Data.GetData();
                request.Referer 
= RequestPageURL;
                request.AllowAutoRedirect 
= false;
                request.UserAgent 
= "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; Maxthon; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
                request.Timeout 
= 20000;

                
if (cookie != null)
                {
                    request.CookieContainer 
= new CookieContainer();
                    request.CookieContainer.Add(cookie);
                }

                Uri u 
= new Uri(StrUrl);

                
if (postdata.Length > 0//包含要提交的数据 就使用Post方式
                {
                    request.ContentType 
= "application/x-www-form-urlencoded"//作为表单请求
                    request.Method = "POST";        //方式就是Post

                    
//把提交的数据换成字节数组
                    Byte[] B = System.Text.Encoding.UTF8.GetBytes(postdata);
                    request.ContentLength 
= B.Length;

                    System.IO.Stream SW 
= request.GetRequestStream(); //开始提交数据
                    SW.Write(B, 0, B.Length);
                    SW.Close();
                }

                response 
= request.GetResponse() as HttpWebResponse;
                
if (CreateCookie)
                    
//cookie = response.Cookies;
                    AddCookieWithCookieHead(ref cookie, response.Headers["Set-Cookie"], request.RequestUri.Host);
                reader 
= new StreamReader(response.GetResponseStream(), Encoding.Default);

                
return reader.ReadToEnd();
            }
            
catch (Exception ex)
            {
                
string x = ex.StackTrace;
            }
            
finally
            {
                
if (response != null)
                    response.Close();
            }

            
return string.Empty;
        }


        
public bool PostDownload(RequestData Data, out string file)
        {
            file 
= null;
            StreamReader reader 
= null;
            HttpWebResponse response 
= null;
            HttpWebRequest request 
= null;
            
try
            {
                
string StrUrl = "http://www.imobile.com.cn/wapdiyringdownload.php";
                request 
= HttpWebRequest.Create(StrUrl) as HttpWebRequest;

                
string postdata = Data.GetData();
                request.Referer 
= StrUrl;
                request.AllowAutoRedirect 
= false;
                request.UserAgent 
= "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; Maxthon; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
                request.Timeout 
= 20000;

                
if (cookie != null)
                {
                    request.CookieContainer 
= new CookieContainer();
                    request.CookieContainer.Add(cookie);
                }

                Uri u 
= new Uri(StrUrl);

                
if (postdata.Length > 0//包含要提交的数据 就使用Post方式
                {
                    request.ContentType 
= "application/x-www-form-urlencoded"//作为表单请求
                    request.Method = "POST";        //方式就是Post

                    
//把提交的数据换成字节数组
                    Byte[] B = System.Text.Encoding.UTF8.GetBytes(postdata);
                    request.ContentLength 
= B.Length;

                    System.IO.Stream SW 
= request.GetRequestStream(); //开始提交数据
                    SW.Write(B, 0, B.Length);
                    SW.Close();
                }

                response 
= request.GetResponse() as HttpWebResponse;
                
string des = response.Headers["Content-Disposition"].Trim();
                file 
= des.Substring(des.IndexOf("filename="+ 9);
                file 
= new Random().Next(100).ToString() + "/" + file;

                System.IO.Stream stream 
= response.GetResponseStream();
                
try
                {
                    
int Filelength = (int)response.ContentLength;

                    
byte[] b = new byte[512];

                    
int nReadSize = 0;
                    nReadSize 
= stream.Read(b, 0512);

                    System.IO.FileStream fs 
= System.IO.File.Create("f:/mobileMusic/" + file);
                    
try
                    {
                        
while (nReadSize > 0)
                        {
                            fs.Write(b, 
0, nReadSize);
                            nReadSize 
= stream.Read(b, 0512);
                        }
                    }
                    
finally
                    {
                        fs.Close();
                    }
                }
                
catch (Exception er)
                {
                    
//Log l = new Log();
                    
//l.writelog("下载文件错误", er.ToString());
                }
                
finally
                {
                    response.Close();
                    stream.Close();
                }
            }
            
catch (Exception ex)
            {
                
string x = ex.StackTrace;
            }
            
finally
            {
                
if (response != null)
                    response.Close();
            }
            
return true;
        }
        
#region GetPage
        
/// <summary>
        
/// 获取源代码
        
/// </summary>
        
/// <param name="url"></param>
        
/// <param name="coding"></param>
        
/// <param name="TryCount"></param>
        
/// <returns></returns>
        public static string GetPage(string url, Encoding encoding, int TryCount)
        {
            
for (int i = 0; i < TryCount; i++)
            {
                
string result = GetPage(url, encoding, null);
                
if (result != null && result != string.Empty)
                    
return result;
            }

            
return string.Empty;
        }

        
/// <summary>
        
/// 获取源代码
        
/// </summary>
        
/// <param name="url"></param>
        
/// <param name="coding"></param>
        
/// <returns></returns>
        public static string GetPage(string url, Encoding encoding, string cookie)
        {
            HttpWebRequest request 
= null;
            HttpWebResponse response 
= null;
            StreamReader reader 
= null;
            
try
            {
                request 
= (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent 
= "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2;)";
                request.Timeout 
= 20000;
                request.AllowAutoRedirect 
= false;
                
if (cookie != null)
                    request.Headers[
"Cookie"= cookie;

                response 
= (HttpWebResponse)request.GetResponse();
                
if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 1024)
                {
                    reader 
= new StreamReader(response.GetResponseStream(), encoding);
                    
string html = reader.ReadToEnd();

                    
return html;
                }
            }
            
catch
            {
            }
            
finally
            {

                
if (response != null)
                {
                    response.Close();
                    response 
= null;
                }
                
if (reader != null)
                    reader.Close();

                
if (request != null)
                    request 
= null;

            }

            
return string.Empty;
        }
        
#endregion
    }

    
public class RequestData
    {
        Hashtable hash 
= new Hashtable();

        
public RequestData()
        {

        }

        
public string GetData()
        {
            
string r = "";

            
foreach (string key in hash.Keys)
            {
                
if (r.Length > 0) r += "&";
                r 
+= key + "=" + hash[key];
            }

            
return r;
        }

        
public void AddField(string Field, string Value)
        {
            hash[Field] 
= Value;
        }


    }
}

转载于:https://www.cnblogs.com/stu-acer/archive/2008/10/11/1308712.html

相关文章:

DataPipeline |《Apache Kafka实战》作者胡夕:Apache Kafka监控与调优

胡夕&#xff0c;《Apache Kafka实战》作者&#xff0c;北航计算机硕士毕业&#xff0c;现任某互金公司计算平台总监&#xff0c;曾就职于IBM、搜狗、微博等公司。国内活跃的Kafka代码贡献者。 前言虽然目前Apache Kafka已经全面进化成一个流处理平台&#xff0c;但大多数的用户…

windows程序移植linux

1&#xff0c;路径名统一用正斜杠“/”。&#xff08;windows下正反斜杠都识别&#xff0c;linux只认正斜杠。&#xff09; 2&#xff0c;统一使用UTF-8格式编码。 vim中无法保存汉字时&#xff0c;可输入下列命令&#xff1a; &#xff1a;set fileencodingprc &#xff1a;se…

完美解决方案 | 完全卸载任何版本office残余文件

采用微软官方给的卸载文件&#xff0c;注意需要能够科学上网 然后再用拼夕夕的安装包重装就能装上&#xff0c;不会提示以下 折腾好久&#xff0c;这次亲测有效 参考文章

Struts2的拦截器只允许有权限用户访问action

1、定义拦截器,继承MethodFilterInterceptor package com.life.stuts.interceptor;import java.util.Map;import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;/*** 如果不是login的adction&#xff0c;使…

ZABBIX(八) Zabbix 通知媒介

一、zabbix报警媒介介绍zabbix触发器到了要发送通知的情况下&#xff0c;需要一个中间介质来接收并传递消息给运维。以前使用的是nagios&#xff0c;通常用脚本发送邮件或者发送飞信来达到报警。在此脚本就是一个媒介了。1、E-mail使用sendmail发送邮件&#xff0c;从这边出去的…

Office Live for Small Business--开启您创业的大门

在我印象中&#xff0c;有一段时间了&#xff0c;我一个人或是和一些朋友在一起聊天的时候&#xff0c;脑子里总是会不由自主地琢磨一个问题&#xff0c;我想这个问题或许也常常困扰很多朋友&#xff0c;那就是“房子首付从哪里来”。我不是一个习惯于伸手跟父母要钱的人&#…

webView加载不出网页的一种可能情况

我的webview的Java代码里有以下内容 Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.webview);savedInstanceState getIntent().getExtras();myurl savedInstanceState.getString("url&qu…

GridView 始终显示 Pager 分页行的一种方法

GridView 是 ASP.NET 2.0 新增加的 Web 控件&#xff0c;拥有比 DataGrid 更多的扩展和改进。使用 GridView 可以很容易的实现数据分页&#xff0c;但是遗憾的是&#xff0c;在缺省情况下&#xff0c;当仅有一页数据时&#xff0c; GridView 不显示 Pager 分页行&#xff0c;这…

php 几十万数据导出到csv

2019独角兽企业重金招聘Python工程师标准>>> 参考资料 &#xff1a; https://blog.csdn.net/tim_phper/article/details/77581071 https://www.imooc.com/wenda/detail/316785 /*** 下载/导出到csv文件* param $title 标题栏标题* param $data : array($count M(表…

恍然大悟之原、反、补

曾在很多书籍中看到过关于原码、反码和补码的介绍&#xff0c;都未能够深入理解。今在Richard Blum编写的《汇编语言程序设计》一书中读到关于带符号整数一节的讲解时&#xff08;确切的说是其中的一句话&#xff09;&#xff0c;的确有茅塞顿开、恍然大悟之感。原文如下&#…

Android中的多线程(字节跳动)

文章目录Handler机制(Android中的消息队列机制)Handler机制为Android系统解决了以下两个问题Handler常用方法Handler的使用补充知识点Handler原理辨析Runnable/Message扩展知识&#xff1a;ANRHandler总结Android中的多线程概念&#xff1a;进程与线程(Process and Thread)Andr…

利用ZYNQ SOC快速打开算法验证通路(5)——system generator算法IP导入IP integrator

一、前言 利用FPGA设计算法一直以来都是热点&#xff0c;同样也是难点。将复杂的数学公式 模型通过硬件系统来搭建&#xff0c;在低延时 高并行性等优势背后极大提高了设计难度和开发周期。Xilinx公司的sysGen&#xff08;system generator&#xff09;工具扩展了MATLAB的simul…

JS下计算当前日期(当天)后N天出现NAN或者undefined的情况

前言&#xff1a; 帮客户做一个订单系统&#xff0c;需要一个日期1&#xff0c;一个日期2&#xff0c;默认情况下日期1为当天&#xff0c;日期2为明天&#xff0c;只是当时有些疑惑的是日期2偶尔会出现NAN的情况&#xff0c;今天在segmentfault.com看到了同样的问题&#xff0c…

VCL 中的 Windows API 函数(6): BeginDeferWindowPos

BeginDeferWindowPos 和 DeferWindowPos、EndDeferWindowPos 是一组一起使用的函数, 可对一组窗口的位置、大小、Z 序等进行调整, 在 ExtCtrls 单元有用到.下面先用常规方法实现对 Panel1 中的一组 Button 进行调整, 然后再用上面三个函数重新实现.本例效果图:代码文件:unit Un…

base64格式的图片数据如何转成图片

base64格式的图片数据如何转成图片 一、总结 一句话总结&#xff1a;不仅要去掉前面的格式串&#xff0c;还需要base64_decode&#xff08;&#xff09;解码才行。 1 // $base_img是获取到前端传递的值2 $base_img str_replace(data:image/jpg;base64,, , $base_img);3 // 设…

拷贝构造函数和赋值函数的一些知识

/*******************拷贝构造函数和赋值运算符重载有以下两个不同之处***************************/ 1.拷贝构造函数生成新的类对象&#xff0c;而赋值运算符不能。 2.由于拷贝构造函数是直接构造一个新的类对象&#xff0c;所以在初始化这个对象之前不用检验源对象是否和新对…

代码重构之三种取代类型码(类、子类、状态对象或策略对象)的方式辨析

1.以类取代类型码 适用情况&#xff1a;类之中有一个数值类型码&#xff0c;但它并不影响类的行为。 重构手段&#xff1a;以一个新的类替换该数值类型码。 重构类图示意&#xff1a; 这里的“不影响类的行为”是什么意思呢&#xff1f; 类型码往往和switch语句一起出现&#…

NHibernate之旅(11):探索多对多关系及其关联查询

本节内容 多对多关系引入多对多映射关系多对多关联查询1.原生SQL关联查询2.HQL关联查询3.Criteria API关联查询结语多对多关系引入 让我们再次回顾在第二篇中建立的数据模型&#xff1a; 在图上&#xff0c;我已经清晰的标注了表之间的关系&#xff0c;上两篇分析Customer和Ord…

自动化运维—saltstack

2019独角兽企业重金招聘Python工程师标准>>> 自动化运维——saltstack 、ansible 一、自动化运维介绍 传统运维&#xff1a;传统运维效率低&#xff0c;大多工作需要人工完成&#xff0c;工作繁琐&#xff0c;容易出错&#xff0c;每日重复做相同的事情&#xff0c;…

史上最浅显易懂的Git教程!

Git初学者很好的一篇教程 mark : ) http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000 转载于:https://www.cnblogs.com/anthony0859/p/3900327.html

狎昵关系和依恋情结辨诠

Inappropriate Intimacy&#xff08;狎昵关系&#xff09; 表现&#xff1a;两个classes过于亲密&#xff0c;花费太多时间去探究彼此的private成分 解决&#xff1a;你可以采用 Move Method 和 Move Field 帮它们划清界线&#xff0c;从而减少狎昵行径。你也可以看看是否运用…

win2000.win2003关闭端口详解--防黑必备

我相信有很多人都不知道自己开了什么端口.更加不知道怎么关闭端口. 你可以用查看端口的软件查看. 也可以通过在运行里输入"cmd" 在弹出的cmd命令行里输入 netstat -an 来查看自己开放端口.ip地址的后面的就是端口号. 以下是我自己写的一篇关于关闭端口的详细步骤和多…

网站基于vs,复选框,单选款

前端代码&#xff1a; <% Page Language"C#" AutoEventWireup"true" CodeFile"Default2.aspx.cs" Inherits"Default2" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or…

thinphp 整合ueditor

我的ueditor是部署在public/editor 部署前台页面 <script type"text/javascript" > var UEDITOR_HOME_URL: "__PUBLIC__/ueditor/" </script><script id"container" name"$des" type"text/plain">这里写你…

笔画宽度变化(C++和matlab算法)

最近一直在看工作方面的书籍&#xff0c;把论文的事情搁置了&#xff0c;之前承诺的贴代码的事一直拖。现在把代码整理发上来&#xff0c;只有核心部分的&#xff0c;都不是我写的&#xff0c;我是网上整理下载的&#xff0c;matlab代码的效果比较差。 全部文件网盘下载地址:ht…

bzoj1227: [SDOI2009]虔诚的墓主人(树状数组,组合数)

传送门 首先&#xff0c;对于每一块墓地&#xff0c;如果上下左右各有$a,b,c,d$棵树&#xff0c;那么总的虔诚度就是$C_k^a*C_k^b*C_k^c*C_k^d$ 那么我们先把所有的点都给离散&#xff0c;然后按$x$为第一关键字&#xff0c;$y$为第二关键字&#xff0c;那么同一横坐标的一定在…

[导入]源代码版本控制(一)

开发过程当中源代码的版本控制一直是个大问题。项目规模小了还好办&#xff0c;人的脑子还能记过来&#xff0c;项目大了&#xff0c;可能用各式各样的表格来记录版本信息和源代码内容&#xff0c;但这个办法本身的文档组织又是个问题&#xff0c;谁来维护&#xff1f;谁来更改…

重构技巧分别能够解决哪些代码味道

1.提炼类可以解决的5种代码味道&#xff1a; 过大类 重复代码 基本类型偏执 令人迷惑的暂时值域 狎昵关系 2.将类内联化可以解决的3种代码味道 冗赘类 夸夸其谈的未来性 霰弹式修改 3.隐藏委托关系解决的2种代码味道 狎昵关系 过度耦合的消息链 4.复制被监视的数据 过大类 5.以…