如何避免循环中断?

时间:2014-03-26 15:31:48

标签: c# .net linq webbrowser-control

我在Windows Forms项目中有一个WebBrowser。它导航表元素中的所有链接。它工作正常;但它在循环中使用break。如何在没有break语句的情况下实现此功能?

注意:在我的实际场景中,如果我们使用该链接提供Navigate命令,则所有链接都将重定向到登录页面。因此,在我的实际场景中,存储所有网址并在之后进行导航对我来说不起作用。

C#代码

public partial class Form1 : Form
{

string websiteUrl = @"C:\Samples_L\MyTableTest.html";
List<string> visitedUrls = new List<string>();
string currentUrl = String.Empty;

private void ExerciseApp(object sender, EventArgs e)
{

    Thread.Sleep(1000);

    if (currentUrl != websiteUrl)
    {
        currentUrl = websiteUrl;
        wb.Navigate(websiteUrl);
    }


    HtmlElement tableElement = wb.Document.GetElementById("four-grid");
    if (tableElement != null)
    {
        foreach (HtmlElement e1 in tableElement.All)
        {
            string x = e1.TagName;
            String idStr = e1.GetAttribute("id");

            if (!String.IsNullOrWhiteSpace(idStr))
            {
                if (idStr.Contains("catalogEntry_img"))
                {
                    string url = e1.GetAttribute("href");
                    if (!visitedUrls.Contains(url))
                    {
                        currentUrl = url;
                        visitedUrls.Add(url);
                        e1.InvokeMember("Click");

                        //Use break when the first match is found
                        break;
                    }
                }
            }
        }
    }

}



private System.Windows.Forms.WebBrowser wb = null;
private Button button1 = null;
private ListBox listBox1 = null;

public Form1()
{

    // button1
    button1 = new Button();
    button1.Location = new Point(20, 430);
    button1.Size = new Size(90, 23);
    button1.Text = "Load and Test";
    button1.Click += new EventHandler(this.button1_Click);

    // listBox1
    listBox1 = new ListBox();
    listBox1.Location = new Point(10, 460);
    listBox1.Size = new Size(460, 200);

    // Web Browser
    wb = new WebBrowser();
    wb.Location = new Point(10, 10);
    wb.Size = new Size(1000, 400);

    //Subscribing for the Document Completed Event
    wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(ExerciseApp);

    // Form1
    this.Text = "Web Browser Test";
    this.Size = new Size(5000, 7100);
    this.Controls.Add(wb);
    this.Controls.Add(button1);
    this.Controls.Add(listBox1);

    currentUrl = websiteUrl;
}

private void button1_Click(object sender, EventArgs e)
{
    listBox1.Items.Add("Loading Web app under test into WebBrowser control");
    wb.Url = new Uri(websiteUrl);

}


}

使用HTML

<html>
<head>

    <style type="text/css">
        table {
            border: 2px solid blue;
        }

        td {
            border: 1px solid teal;
        }
    </style>

</head>
<body>

    <table id="four-grid">
        <tr>
            <td>
                <a href="https://stackoverflow.com/users/696627/lijo" id="catalogEntry_img63664" class="itemhover"
                    onfocus="showPopupButton('category_63664');"
                    onkeydown="shiftTabHidePopupButton('category_63664',event);">

                    <img src="ssss"
                        alt="G" width="70" />
                </a>
            </td>
            <td>
                <a href="http://msdn.microsoft.com/en-US/#fbid=zgGLygxrE84" id="catalogEntry_img63665" class="itemhover"
                    onfocus="showPopupButton('category_63665');"
                    onkeydown="shiftTabHidePopupButton('category_63665',event);">

                    <img src="ssss"
                        alt="Y" width="70" />
                </a>
            </td>
        </tr>
        <tr>
            <td>
                <a href="https://www.wikipedia.org/" id="catalogEntry_img63666" class="itemhover"
                    onfocus="showPopupButton('category_63666');"
                    onkeydown="shiftTabHidePopupButton('category_63666',event);">

                    <img src="ssss"
                        alt="B" width="70" />
                </a>
            </td>
            <td>
                <a href="http://www.keralatourism.org/" id="catalogEntry_img63667" class="itemhover"
                    onfocus="showPopupButton('category_63667');"
                    onkeydown="shiftTabHidePopupButton('category_63667',event);">

                    <img src="ssss"
                        alt="A" width="70" />
                </a>
            </td>
        </tr>
    </table>
</body>

</html>

参考

  1. Next using LINQ approach

2 个答案:

答案 0 :(得分:4)

您可以将其重构为查询,使代码的意图更加清晰:

var nextElement = tableElement.All
    .Where(element => element.GetAttribute("id") != null &&
        element.GetAttribute("id").Contains("catalogEntry_img") &&
        !visitedUrls.Contains(element.GetAttribute("href")))
    .FirstOrDefault();

if(nextElement != null)
{
    visitedUrls.Add(nextElement.GetAttribute("href"));
    nextElement.InvokeMember("Click");
    currentUrl = nextElement.GetAttribute("href");
}

我还建议将visitedUrls更改为HashSet,而不是列表,因为它是一种更有效的数据结构,用于简单地确定项目是否在一组项目中。

答案 1 :(得分:0)

如果迭代一系列值并希望在找到满足条件的值时立即退出,则通常使用break:

foreach(var a in list) {
   if(test(a)) {
       // use a
       break;
   }
}

有时它可能是不受欢迎的,你可以使用它:

bool found = false;
foreach(var a in list) {
   if(found && test(a)) {
       // use a
       found = true;
   }
}

甚至:

bool found = false;
foreach(var a in list) {
   if(test(a)) {
       if(found) {
           // use a
           found = true;
       }
   }
}

第一个版本可以在找到合适的元素后跳过迭代。其他两个变体继续迭代甚至检查所有元素。几乎在所有情况下,这都会浪费处理能力。但是请看一下您实际上可能想要使用第三个变体的情况:http://en.wikipedia.org/wiki/Timing_attack