2012-01-16 16 views
0

我目前在我的應用程序上使用此代碼很好地循環瀏覽頁面,並獲取表單輸入值的標籤,然後將值打印到富文本框。如何重新配置​​代碼以輸出特定值而不是集合

我現在試圖修改代碼,如果標籤包含特定名稱,則爲我提供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

我覺得你只是想在最後一個循環改變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 
+0

救援。感謝competent_tech :) – 2012-01-17 17:18:41

+0

對不起...我說話太快..這不是我所期待的。我試圖做的是讓應用程序做..如果標籤包含(「用戶名」)(「用戶」)或(「U」)中的任何單詞,然後獲取輸入字段的ID。有任何想法嗎? – 2012-01-18 00:36:55

+0

好吧,我已經更新了答案,向你展示了你需要做的事情。 – 2012-01-18 04:05:36

相關問題