我想用一个浏览器(不是同时)完全加载3个网站并完成一些任务。
我的代码;
string[] websites =
{
"www.facebook.com", "www.bug.hr", "www.htmlgoodies.com"
};
string[] inputs =
{
"first", "second", "third"
};
private void Form1_Load(object sender, EventArgs e)
{
Browser1.Navigate(websites[0]);
}
private void Browser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (Browser1.Url.ToString().Contains(websites[0]))
{
while (Browser1.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
Browser1.Document.GetElementById("email").SetAttribute("value", inputs[0]);
Browser1.Navigate(websites[1]);
}
if (Browser1.Url.ToString().Contains(websites[1]))
{
while (Browser1.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
Browser1.Document.GetElementById("mainsearchtext").SetAttribute("value", inputs[1]);
Browser1.Navigate(websites[2]);
}
if (Browser1.Url.ToString().Contains(websites[2]))
{
Browser1.Document.GetElementById("search-input").SetAttribute("value", inputs[2]);
}
SCOND WAY;
int n;
private void Browser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
n++;
if (n == 1)
{
Browser1.Document.GetElementById("email").SetAttribute("value", inputs[0]);
Browser1.Navigate(websites[1]);
}
if (n == 2)
{
Browser1.Document.GetElementById("mainsearchtext").SetAttribute("value", inputs[1]);
Browser1.Navigate(websites[2]);
}
if (n == 3)
{
Browser1.Document.GetElementById("search-input").SetAttribute("value", inputs[2]);
}
第二种方式问题是,n有时可能与预期不同。
我在加载第二和第三个网站时遇到问题。我也尝试了另一种方法,但不起作用。所以我的目标是一个接一个地打开页面,并在每个页面上执行一些任务。如果您有其他方式,我将不胜感激。
答案 0 :(得分:0)
也许尝试这样的事情:
int current = 0;
string[] websites = { "www.facebook.com", "www.bug.hr", "www.htmlgoodies.com" };
string[] elements = { "email", "mainsearchtext", "search-input" };
string[] inputs = { "first", "second", "third" };
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate(websites[current]);
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
timer1.Interval = 250;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
{
timer1.Stop();
webBrowser1.Document.GetElementById(elements[current]).SetAttribute("value", inputs[current]);
if (++current < websites.Length)
{
webBrowser1.Navigate(websites[current]);
}
}
}