获取不带' For Each'的HTML元素环

时间:2014-09-20 03:16:31

标签: vb.net winforms visual-studio-2010 visual-studio-2013

我已经开始在Visual Basic中进行一些编程了,我需要一些帮助。这可能是一个简单的问题,但我无法弄清楚这一点。

所以我创建了一个网络浏览器,我希望在Facebook上获取一个人的个人资料图片,并将其显示在图片框上,以及该人的姓名并将其显示在TextBox上。之后,程序应将图片保存在硬盘上的文件夹中。

Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted

 Dim elemCollection As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("img")
    Dim fbPath As String = "C:\Users\" + Environment.UserName.ToString + "\Documents\FB Images\"


    For Each curElement As HtmlElement In elemCollection

        If curElement.OuterHtml.Contains("profilePic img") Then
            PictureBox1.ImageLocation = curElement.GetAttribute("src") 'Showing the profile pic in picture box
            TextBoxName.Text = curElement.GetAttribute("alt") 'Showing the name in a textbox
            Dim NumberOfFiles As Integer = System.IO.Directory.GetFiles(fbPath).Length 
            Dim bmp As New Bitmap(PictureBox1.Width, PictureBox1.Height)
            PictureBox1.DrawToBitmap(bmp, PictureBox1.ClientRectangle)
            bmp.Save(System.IO.Path.Combine(fbPath, CStr(NumberOfFiles) + TextBoxName.Text + ".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg)
        End If

    Next
End Sub

因此,程序应根据文件夹路径中的文件数(例如'1 George Johnson.jpg')使用文件名保存图片。但是会发生什么,它会保存5个不同的图像,因为我猜有多个HTML元素匹配这些属性,因此For Each循环会带来更多结果。

有没有办法在不使用这个循环的情况下获取HTML元素并获得我想要的特定元素?

1 个答案:

答案 0 :(得分:0)

如果您只想第一次属性的if语句为true,请在End If之前添加“Exit For”行。