如何让循环移动到下一个可用的ID,而不是连续进行? [英] How to have loop move to the next id available rather than doing the same continuously?
本文介绍了如何让循环移动到下一个可用的ID,而不是连续进行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在,当我运行此命令时,它会每2秒单击一次相同的按钮.我试图弄清楚如何继续使用下一个ID,而不是继续执行找到的第一个ID,然后破坏它.这是我的代码:
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;
}
}
}
推荐答案
将代码更改为此...
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();
}
}
顺便说一句,我不知道HtmlElementCollection是否具有删除"方法...如果没有,只需使用通用List<>或ArrayList等.
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.
这篇关于如何让循环移动到下一个可用的ID,而不是连续进行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文