using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace Quick
{
public partial class FormMain : Form
{
HtmlElementCollection link;
Boolean flag;
Boolean loading;
public FormMain()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
flag = false;
loading=true;
//循环执行任务
for (int page = 1; page <= 4;page++)
{
while(loading)
{
loading = false;
this.webBrowser.Navigate("http://www.haosou.com/s?ie=utf-8&shb=1&src=360sou_newhome&q=12&pn="+page);
this.webBrowser.ScriptErrorsSuppressed = true;
if (flag)
break;
}
}
}
private void FormMain_Load(object sender, EventArgs e)
{
//System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
//ThreadStart是一个无参无返回值的委托。
//ThreadStart ts = new ThreadStart(task);
//初始化Thread的新实例,并通过构造方法将委托ts做为参数赋初始值。
//Thread td = new Thread(ts); //需要引入System.Threading命名空间
//运行委托
//td.Start();
//循环执行任务
//while (true)
//{
// flag = false;
// this.webBrowser.Navigate("http://www.haosou.com/s?ie=utf-8&shb=1&src=360sou_newhome&q=台湖");
// this.webBrowser.ScriptErrorsSuppressed = true;
//等待10S,等待页面加载完成
//Thread.Sleep(10000);
//停止20S,进行下一个任务
// Thread.Sleep(20000);
// }
}
public void task()
{
//循环执行任务
while (true)
{
flag = false;
this.webBrowser.Navigate("http://www.haosou.com/s?ie=utf-8&shb=1&src=360sou_newhome&q=12");
this.webBrowser.ScriptErrorsSuppressed = true;
//等待10S,等待页面加载完成
Thread.Sleep(10000);
//停止20S,进行下一个任务
Thread.Sleep(20000);
}
}
private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{/*
foreach (HtmlElement archor in this.webBrowser.Document.Links)
{
archor.SetAttribute("target", "_self");
}
foreach (HtmlElement form in this.webBrowser.Document.Forms)
{
form.SetAttribute("target", "_self");
}
link = this.webBrowser.Document.GetElementsByTagName("a");
for (int ii = 0; ii < link.Count; ii++)
{
if (link[ii].GetAttribute("href").Contains("www.xingzuowu.com"))
{
link[ii].InnerHtml = "" + link[ii].InnerHtml + "";
link[ii].InvokeMember("click");
//已经找到,退出循环
break;
}
}
loading = true;*/
}
bool load = true; //该变量表示网页是否正在加载.
string html = string.Empty;
private void buttonLoop_Click(object sender, EventArgs e)
{
String[] urls = { "http://www.haosou.com/s?q=12&pn=1", "http://www.haosou.com/s?q=12&pn=2", "http://www.haosou.com/s?q=12&pn=3" };
webBrowser.Navigated += new WebBrowserNavigatedEventHandler(webBrowser_Navigated);
foreach (string url in urls)
{
load = true; //表示正在加载
webBrowser.Navigate(url);
this.webBrowser.ScriptErrorsSuppressed = true;
while (load)
{
Application.DoEvents();//等待本次加载完毕才执行下次循环.
}
}
}
void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
html = webBrowser.DocumentText; //获取到的html.
MessageBox.Show(html);
load = false;//在加载完成后,将该变量置为false,下一次循环随即开始执行.
}
}
}
效果是:在完成第一个网页后,再对第二个网页进行访问,测试成功!