如何重新配置​​代码以输出特定值而不是集合

时间:2012-01-16 21:19:52

标签: vb.net browser html-agility-pack

我目前在我的应用上使用此代码非常适合循环浏览页面并获取表单输入值的标签,然后将值打印到富文本框中。

我现在正在尝试修改代码,以便在标签包含特定名称时为ID提供值。

例如,如果输入字段前的标签包含单词Username,那么我希望应用程序输出输入字段的ID,而不仅仅是所有带标签的ID。

这是我目前的代码:

    Dim web As HtmlAgilityPack.HtmlWeb = New HtmlWeb()
    Dim doc As HtmlAgilityPack.HtmlDocument = web.Load("http://shaggybevo.com/board/register.php")

    Dim nodes As HtmlNodeCollection
    ' Keeps track of the labels by the associated control id     

    Dim labelText As New System.Collections.Generic.Dictionary(Of String, String)
    ' First, get the labels     

    nodes = doc.DocumentNode.SelectNodes("//label")
    If nodes IsNot Nothing Then
        For Each node In nodes
            If node.Attributes.Contains("for") Then
                Dim sFor As String
                ' Extract the for value                 
                sFor = node.Attributes("for").Value
                ' If it does not exist in our dictionary, add it                 
                If Not labelText.ContainsKey(sFor) Then

                    labelText.Add(sFor, node.InnerText)
                End If
            End If
        Next
    End If

    nodes = doc.DocumentNode.SelectNodes("//input")

    Dim sbText As New System.Text.StringBuilder(500)
    If nodes IsNot Nothing Then
        For Each node In nodes
            ' See if this input is associated with a label             
            If labelText.ContainsKey(node.Id) Then
                ' If it is, add it to our collected information                 
                sbText.Append("Label = ").Append(labelText(node.Id))
                sbText.Append(", Id = ").Append(node.Id)
                sbText.AppendLine()
            End If
        Next
    End If




    RichTextBox1.Text = sbText.ToString

1 个答案:

答案 0 :(得分:1)

我认为您只想将最后一个循环中的if语句更改为:

' See if this input is associated with a label             
If labelText.ContainsKey(node.Id) Then
    Dim sLabel As String

    sLabel = labelText(nodeId)

    ' If it is, see if the label name is one that we are looking for
    If sLabel.IndexOf("username", StringComparison.InvariantCultureIgnoreCase) >= 0 OrElse sLabel.IndexOf("user", StringComparison.InvariantCultureIgnoreCase) >= 0 OrElse sLabel.IndexOf("u", StringComparison.InvariantCultureIgnoreCase) >= 0 Then
        ' Report the node associated 
        Console.WriteLine("Username is associated with node id " & node.Id)
        ' And bail out of the loop
        Exit For
     End If
End If