【发布时间】:2016-11-10 16:09:59
【问题描述】:
我开发了一个应用程序,使用 WebClient 从具有某种模式的网站下载多个图像。 当我开始做这个时,我的想法是一个快速简单的应用程序,所以我制作了一个表单:
- 网络浏览器 (WB)
- 多行文本框可放置多个要抓取的网址
- 列表框存储每张照片的链接
- 用于选择目标路径的文本框
- 启动进程的按钮
这很简单,我只需要使用 For + HtmlElement + WB.Document.All 找到每张照片的标签。获得所有链接后,我使用 WebClient 非常快速地下载它们(Client.DownloadFile(路径,文件名))。它完美无缺。
现在应用程序更大了,它有更多的网站要抓取,我想使用 BackgroundWorker 来管理它。 我开始学习 BGWorker 是如何工作的,我注意到我不能使用像 WebBrowser 这样的控件,它给出了一个异常,所以我不能使用 WB.Document.All 来获取链接。
我在 Codeproject 中发现了一个如何使用 BGWorker 下载文件的惊人示例,具体如下:
http://www.codeproject.com/Articles/17979/Downloading-Files-in-NET-With-All-Information-Prog
他使用 HttpWebRequest,如果我首先需要获取链接,这似乎更难实现。
我的问题是:我应该重新编码应用程序以使用 HttpWebRequest 还是可以调整当前代码(涉及 WebBrowser)以使用 BGWorker?如果可以将 WebBrowser 与 BGWorker 一起使用,那么哪种方法是正确的?
我当前的相关代码(单击按钮时调用此函数)。我只写了必要的行:
Function ExtractLicensePlate()
Dim Client As New WebClient
Dim totalPhotos As Integer = 0
Dim finalPlate As String = "[no licenseplate found]"
Dim totalCarsList As Integer = txtURLs.Lines.Where(Function(l) Not String.IsNullOrWhiteSpace(l)).Count()
For i = 0 To totalCarsList - 1
WB.Navigate(txtURLs.Lines(i))
WaitForPageLoad()
For Each ele As HtmlElement In WB.Document.All
'ALD
If comboProviders.SelectedIndex = 0 Then
If ele.GetAttribute("src").ToLower.Contains("iddoc") Then
Dim imgsrc As String = ele.GetAttribute("src")
lstPhotos.Items.Add(imgsrc)
End If
'get license plate to make folders
If ele.GetAttribute("action").ToLower.Contains("matr=") Then
Dim fullURLname As String = ele.GetAttribute("action")
finalPlate = fullURLname.Split("=")(3).Substring(0, 7)
End If
End If
Next
If (Not Directory.Exists(txtDirectory.Text & "\" & finalPlate)) Then
If Not (finalPlate = "[no licenseplate found]") Then
Directory.CreateDirectory(txtDirectory.Text & "\" & finalPlate)
End If
End If
For j = 0 To lstPhotos.Items.Count - 1
Client.DownloadFile(lstPhotos.Items(j).ToString, txtDirectory.Text & "\" & finalPlate & "\" & finalPlate & j & ".jpg")
Client.Dispose()
Next j
lstPhotos.Items.Clear()
Next i
Return 0
End Function
任何帮助将不胜感激。
谢谢大家。
【问题讨论】:
-
我的评论“主要基于意见”,但对于最近的 .NET 框架 (4.5+) 上的新代码,我会使用
HttpClient和Task而不是WebClient/@987654326 @ 和BackgroundWorker。我不会使用WebBrowser,除非我想向用户展示网页——你可以考虑使用 HTML Agility Pack 从下载的 HTML 中提取链接。不知道这是否有帮助! :-) -
是的,当然,欢迎各种意见 :-)。感谢您的建议!
标签: vb.net httpwebrequest backgroundworker webclient