WebBrowser从文件加载和显示URL

时间:2016-08-21 13:34:02

标签: vb.net visual-studio webbrowser-control

我想在文本文件中加载一个URL列表。我已经使用>>> a = ["foo", "bar"] >>> b = [1, 2, 3] >>> [(x,y) for x in a for y in b] [('foo', 1), ('foo', 2), ('foo', 3), ('bar', 1), ('bar', 2), ('bar', 3)] 循环完成了这项工作,但我希望浏览器在转到下一个URL之前先完全加载页面。这是我的代码:

For Each

它不显示任何内容。我尝试使用:

For Each url in File.ReadAllLines("urls.txt")
    Browser.Navigate(url)
Next

它显示页面,但第一行是唯一加载的行。

1 个答案:

答案 0 :(得分:2)

如果您希望在另一个网址之后导航到每个网址,则最好将所有网址存储在类级别数组中并订阅WebBrowser.DocumentCompleted event,然后跟踪您当前所在的网址索引一个班级Integer变量。

当引发DocumentCompleted事件时,您只需递增整数变量并从数组的下一项加载URL。

Public Class Form1
    Dim URLs As String()
    Dim UrlIndex As Integer = 0

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        URLs = File.ReadAllLines("urls.txt")
        WebBrowser1.Navigate(URLs(UrlIndex))
    End Sub

    Private Sub WebBrowser1_DocumentCompleted(sender As System.Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        UrlIndex += 1
        If UrlIndex >= URLs.Length Then
            UrlIndex = 0 'Go back to the beginning.
        End If

        WebBrowser1.Navigate(URLs(UrlIndex))
    End Sub
End Class

要为其添加延迟以使每个网址显示一段时间,您可以使用Timer (感谢Werdna提出主题)

Private Sub WebBrowser1_DocumentCompleted(sender As System.Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
    UrlIndex += 1
    If UrlIndex >= URLs.Length Then
        UrlIndex = 0 'Go back to the beginning.
    End If

    WebBrowser1.Navigate(URLs(UrlIndex))
    Timer1.Stop()
End Sub

只需设置计时器Interval property即可更改网站的显示时长(以毫秒为单位)。