问题
Right now when I run this it keeps clicking on the same button every 2 seconds. I'm trying to figure out how I can go on to the next ID rather than it keep doing the first one it finds then breaking. Here is my code:
private void button2_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
HtmlDocument doc = webBrowser1.Document;
HtmlElementCollection links = doc.GetElementsByTagName("a");
foreach (HtmlElement link in links)
{
if (link.GetAttribute("id").Contains("user"))
{
link.InvokeMember("click");
break;
}
}
}
回答1:
Change your code to this...
//HtmlElementCollection links = null;
List<HtmlElement> links = null;
private void button2_Click(object sender, EventArgs e)
{
// This way you only get the links once.
//links = webBrowser1.Document.GetElementsByTagName("a");
links = new List<HtmlElement>(
webBrowser1.Document.GetElementsByTagName("a")
.OfType<HtmlElement>());
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
HtmlElement linkToClick = null;
foreach (HtmlElement link in links)
{
if (link.GetAttribute("id").Contains("user"))
{
linkToClick = link;
break;
}
}
// did I find a link?
if (linkToClick != null)
{
// Remove it from the list so you don't click it again.
links.Remove(linkToClick);
link.InvokeMember("click");
}
else
{
// Stop the timer since there are no more items.
timer1.Stop();
}
}
By the way, I don't know if HtmlElementCollection has a "Remove" method... if it doesn't, simply use a generic List<> or an ArrayList, etc.
回答2:
One option would be to add a List.
Before you click the button, check to see if its name is in the list. If so, don't click.
Each time you click the button, add its name to the list.
来源:https://stackoverflow.com/questions/11025617/how-to-have-loop-move-to-the-next-id-available-rather-than-doing-the-same-contin