//PS 需要引用HtmlAgilityPack.dll 文件,可自行在網上下載 public partial class GrabInterface : Form { public int number = 1; public GrabInterface() { InitializeCompone ...
//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);//去掉
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;
}
}