我编写了代码,在此页面上搜索关键字"Visual Basic Help",如果它包含这些关键字,请单击链接。
但是我需要补充的是,如果没有链接包含这些关键字,则必须刷新页面。
我认为我需要添加一个If
语句,但我不确定如何添加,因为这个循环可以一直持续下去,直到找到关键字。
我写了这段代码:
WebBrowser1.Navigate("https://stackoverflow.com/")
For Each Mylink1 As HtmlElement In WebBrowser1.Document.Links
If Mylink1.OuterHtml.Contains("visual basic help") Then
WebBrowser1.Navigate(Mylink1.GetAttribute("href"))
End If
Next
但是我需要重写它,以便如果WebBrowser网页上没有包含"Visual Basic help"的链接,它会刷新"https://stackoverflow.com/"并再次搜索"Visual Basic Help"。
有人能帮助我吗?
首先,您应该将其放在 WebBrowser 的 DocumentCompleted
事件中,以便仅在下载整个网页时运行代码。
其次,您可以添加一个Boolean
,指示是否已找到链接,然后在循环之后,您可以检查该Boolean
是否设置为 true。如果没有,您只需刷新 Web 浏览器。
要使用按钮激活它,只需在检查它时添加事件处理程序,并在找到链接时将其删除。
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
If WebBrowser1.Url.ToString().ToLower() = "http://stackoverflow.com/" 'Making sure that we're on the correct page, to avoid constant updating while we are on another page.
Dim LinkFound As Boolean = False 'Our boolean indicating wether a link has been found or not.
For Each Mylink1 As HtmlElement In WebBrowser1.Document.Links
If Mylink1.OuterHtml.ToLower().Contains("visual basic help") Then 'ToLower() is making sure that the match is case-insensitive.
LinkFound = True 'A link was found.
WebBrowser1.Navigate(Mylink1.GetAttribute("href"))
RemoveHandler WebBrowser1.DocumentCompleted, AddressOf WebBrowser1_DocumentCompleted 'Remove the handler to stop the checking for links.
Exit For 'No more looping needed.
End If
Next
If LinkFound = False Then
WebBrowser1.Navigate(WebBrowser1.Url) 'No link was found, retry. Using Navigate so that DocumentCompleted will be continuously called.
End If
End If
End Sub
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
AddHandler WebBrowser1.DocumentCompleted, AddressOf WebBrowser1_DocumentCompleted 'Add handler to the DocumentCompleted event so that it will execute the link checking code.
WebBrowser1.Navigate("http://stackoverflow.com/")
End Sub