C# 爬虫

//PS   需要引用HtmlAgilityPack.dll 文件,可自行在网上下载

public partial class GrabInterface : Form
{
public int number = 1;
public GrabInterface()
{
InitializeComponent();
this.Load += GrabInterface_Load;
}

//定时器
System.Timers.Timer myTimer;

//定义委托,防止两线程之间控件赋值冲突
public delegate void Action<in T>(T obj);
public void ActionRead(int t)
{
this.lbl_ok.Text = "正在读取中,请稍后...";
this.btn_sure.Enabled = false;
}
public void ActionFinall(int t)
{
this.lbl_ok.Text = "读取完毕";
this.btn_sure.Enabled = false;
}
public static bool result = true;//设置定时器点击按钮时执行,避免重复执行定时器导致时间混乱
private void btn_sure_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.txt_url.Text))
{
this.lbl_ok.Text = "请选择需要读取的文件";
return;
}
List<string> list_read = TXTHelper.Read(this.txt_url.Text);
if (result)
{
myTimer = new System.Timers.Timer(1000 * 40);//定时周期
myTimer.Elapsed += btn_sure_Click;//
myTimer.AutoReset = true; //是否不断重复定时器操作
myTimer.Enabled = true;//开启计时器
result = false;
}

number++;
Action<int> action = new Action<int>(ActionRead);
Invoke(action, number);

try
{
#region 抓取网页数据
if (list_read != null && list_read.Count > 0)
{
for (int i = 0; i < list_read.Count; i++)
{
string url = list_read[i];
List<string> list = new List<string>();
HtmlWeb webClient = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = GetUrltoHtml(url);
HtmlNodeCollection hrefList = doc.DocumentNode.SelectNodes("//table");
if (hrefList != null)
{
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table"))
{
foreach (HtmlNode row in table.SelectNodes(".//tr")) // 注意 .//tr 读取当前tr,如果为//tr节点 则读取所有的tr节点
{
string name = "";
if (row.SelectNodes("th") == null)//不存在
{
if (row.SelectNodes("td") != null)
{
foreach (HtmlNode cell in row.SelectNodes("td"))
{
Regex htmlSpaceReg = new Regex("\\ \\;", RegexOptions.Compiled | RegexOptions.IgnoreCase);//去掉&nbsp;
name += Regex.Replace((Regex.Replace(cell.InnerText.Trim(), @"\s", "")), @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase) + "\t";
}
list.Add(name);
}
}
}
}
string filename = "";
for (int j = 0; j < list.Count; j++)
{
filename += list[j] + "\n";
}
string sort = DateTime.Now.ToString("yyyyMMddHH").ToString() + number.ToString();
TXTHelper.SavaProcess(filename, sort);
}
}
Action<int> action1 = new Action<int>(ActionFinall);
Invoke(action1, number);
}
#endregion
}
catch (Exception ex)
{
Console.WriteLine("错误" + ex.Message + "");
}
}

private void timer1_Tick(object sender, EventArgs e)
{

}

//选择文件
private void btn_choose_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;//该值确定是否可以选择多个文件
dialog.Title = "请选择电子文档excel";
dialog.Filter = "所有文件(*.txt)|*.txt";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txt_url.Text = dialog.FileName;
}
}

public Thread t1;
public Thread t2;


public static ManualResetEvent eventAB = new ManualResetEvent(false);
private void GrabInterface_Load(object sender, EventArgs e)
{
//抓取代理ip
t1 = new Thread(new ThreadStart(RedirHelper.getProxyList));
t2 = new Thread(new ThreadStart(RedirHelper.YanzhengIp));//验证代理ip
t1.Start();
Thread.Sleep(1000);
t2.Start();
}

private void btn_stop_Click(object sender, EventArgs e)
{
//释放资源
if (myTimer != null)
{
myTimer.Close();
myTimer.Dispose();
}
Application.Exit();
}

public HtmlAgilityPack.HtmlDocument GetUrltoHtml(string Url)
{
List<RedirHelper.proxy> list = RedirHelper.masterPorxyList;
List<RedirHelper.proxy> list_proxy = RedirHelper.list_proxy;//有效的代理ip集合
//if (list_proxy != null && list_proxy.Count > 0)
//{
HtmlAgilityPack.HtmlDocument doc = null;
bool isok = true;
while (isok)
{
try
{
Random index = new Random();
int num = index.Next(0, list_proxy.Count);
System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
WebProxy myProxy = new WebProxy(list_proxy[num].ip, list_proxy[num].port);
wReq.Proxy = myProxy;
wReq.Timeout = 5000;
System.Net.WebResponse wResp = wReq.GetResponse();
System.IO.Stream respStream = wResp.GetResponseStream();
using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding("UTF-8")))
{
HtmlWeb webClient = new HtmlWeb();
doc = webClient.Load(Url);
isok = false;
if (!string.IsNullOrEmpty(lbl_message.Text))
{
lbl_ok.Text = "正在读取中,请稍后...";
lbl_message.Text = "";
}
return doc;
}
}
catch (Exception ex)
{
lbl_ok.Text = "";
lbl_message.Text = "提示:" + ex.Message + "正在尝试重新连接";
isok = false;
//this.btn_sure.Enabled = true;
//myTimer.Close();
}
}
return doc;
//}
//else
//{
lbl_ok.Text = "";
lbl_message.Text = "提示:未获取到有效的代理IP";
this.btn_sure.Enabled = true;
myTimer.Close();
return null;
//}

}
}

 

/// <summary>
/// 读取代理IP,并验证代理IP的可用性
/// </summary>

public static class RedirHelper
{
public static List<proxy> masterPorxyList = new List<proxy>();//代理ip集合
public static List<proxy> list_proxy = new List<proxy>();//有效的代理ip集合

//代理IP网址
private static string address_ip3366 = "http://www.ip3366.net/?stype=1&page={0}";
//代理IP类
public class proxy
{
public string ip { get; set; }

public int port { get; set; }

public string speed { get; set; }

public proxy(string pip, int pport, string speed)
{
this.ip = pip;
this.port = pport;
this.speed = speed;
}
}

/// <summary>
/// 验证代理IP是否有效的方法
/// </summary>
/// <param name="IP"></param>
/// <param name="port"></param>
/// <returns></returns>
public static void YanzhengIp()
{
bool isok = true;
int index = 0;
while (isok)
{
try
{
if (masterPorxyList != null && masterPorxyList.Count > 0)
{
//设置代理IP
WebProxy proxyObject = new WebProxy(masterPorxyList[index].ip, masterPorxyList[index].port);
//向指定地址发送请求
HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create("http://www.baidu.com");
HttpWReq.Proxy = proxyObject;
HttpWReq.Timeout = 3000;
HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
using (StreamReader sr = new StreamReader(HttpWResp.GetResponseStream(), Encoding.UTF8))
{
proxy temp = new proxy(masterPorxyList[index].ip, masterPorxyList[index].port, "");
list_proxy.Add(temp);
list_proxy = list_proxy.Where((x, i) => list_proxy.FindIndex(z => z.ip == x.ip) == i).ToList();//去重
isok = true;
}
}
}
catch (Exception ex)
{
isok = true;
Console.WriteLine(ex.Message);
}
index++;
if (index == masterPorxyList.Count)
{
index = 0;
list_proxy.Clear();//清除集合数据重新赋值
}
}
}

/// <summary>
/// 抓取代理Ip,分页
/// </summary>
/// <param name="pageIndex">分页</param>
/// <returns></returns>
/// object index,System.Timers.ElapsedEventArgs e
public static void getProxyList()
{
List<proxy> proxy_count = new List<proxy>();
while (true)
{
for (int i = 1; i <= 2; i++)
{
string urlCombin = string.Format(address_ip3366, i);
string catchHtml = catchProxIpMethord(urlCombin, "");
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(catchHtml);
HtmlNodeCollection hrefList = doc.DocumentNode.SelectNodes("//table");
if (hrefList != null)
{
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table"))
{
// .// tr 获取当前table下面的,//tr 检索整个界面的tr
foreach (HtmlNode row in table.SelectNodes(".//tr"))
{
if (row.SelectNodes("th") == null)
{
if (row.SelectNodes("td") != null)
{
string ip = row.SelectNodes("td")[0].InnerText.Trim().ToString();
int port = Convert.ToInt32(row.SelectNodes("td")[1].InnerText.Trim());
proxy temp = new proxy(ip, port, "");
proxy_count.Add(temp);
}
}
}
}
}
}
masterPorxyList = proxy_count.Where((x, j) => proxy_count.FindIndex(z => z.ip == x.ip) == j).ToList();//去重
}
}
//抓网页方法
public static string catchProxIpMethord(string url, string encoding)
{
string htmlStr = "";
try
{
if (!String.IsNullOrEmpty(url))
{
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream datastream = response.GetResponseStream();
Encoding ec = Encoding.Default;
if (encoding == "UTF8")
{
ec = Encoding.UTF8;
}
else if (encoding == "Default")
{
ec = Encoding.Default;
}
else
{
ec = Encoding.GetEncoding("GB2312");
}
StreamReader reader = new StreamReader(datastream, ec);
htmlStr = reader.ReadToEnd();
reader.Close();
datastream.Close();
response.Close();
}
}
catch { }
return htmlStr;
}
}

/// <summary>
/// 读取过保存值到txt中
/// </summary>

public class TXTHelper
{
public static String SavaProcess(string data, string sort)
{
if (!string.IsNullOrEmpty(data))
{
System.DateTime currentTime = System.DateTime.Now;
//获取当前日期的前一天转换成ToFileTime
string strYMD = currentTime.ToString("yyyyMMddHHmmssfff");
//按照日期建立一个文件名
string FileName = strYMD + ".txt";
//获取当前项目所在磁盘
string CurDir = System.Windows.Forms.Application.StartupPath.Substring(0, System.Windows.Forms.Application.StartupPath.IndexOf(':')) + ":\\" + @"SaveDir";
//判断路径是否存在
if (!System.IO.Directory.Exists(CurDir))
{
System.IO.Directory.CreateDirectory(CurDir);
}
string name = CurDir + "\\" + @"" + sort + "";
if (!System.IO.Directory.Exists(name))
{
System.IO.Directory.CreateDirectory(name);
}
CurDir = name;
//不存在就创建
String FilePath = CurDir + "\\" + FileName;
////文件覆盖方式添加内容
System.IO.StreamWriter file = new System.IO.StreamWriter(FilePath, false);
//保存数据到文件
file.Write(data);
//关闭文件
file.Close();
//释放对象
file.Dispose();
return FilePath;
}
else
{
return "";
}
}
/// <summary>
/// 读取txt文件
/// </summary>
/// <param name="path"></param>
/// <returns></returns>

public static List<string> Read(string path)
{
StreamReader sr = new StreamReader(path, Encoding.Default);
String line;
List<string> list = new List<string>();
while ((line = sr.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line.ToString()))
{
list.Add(line.ToString());
}
}
list = list.Distinct().ToList();
return list;
}
}

posted @ 2019-05-13 19:16  情殇メ传说  阅读(1512)  评论(0编辑  收藏  举报