How to have loop move to the next id available rather than doing the same continuously?

老子叫甜甜 提交于 2020-01-06 20:01:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!