.Net - WebClient或HttpWebRequest获取内容

时间:2016-11-10 16:09:59

标签: vb.net httpwebrequest backgroundworker webclient

我开发了一个应用程序,使用WebClient从带有模式的网站下载多个图像。 当我开始使用它时,我的想法是一个快速简单的应用程序,因此我创建了一个表单:

  • WebBrowser(WB)
  • 用于放置多个网址以进行抓取的多行文字框
  • 存储每张照片链接的列表框
  • 用于选择目标路径的文本框
  • 启动流程的按钮

很简单,我只需要使用For + HtmlElement + WB.Document.All找到每张照片的标签。一旦我获得了所有链接,我就使用WebClient快速下载它们(Client.DownloadFile(path,filename))。它完美无瑕。

现在应用程序更大,它有更多的网站可以抓取,我想使用BackgroundWorker来管理它。 我开始学习BGWorker是如何工作的,我注意到我不能使用像WebBrowser这样的Control,它给出了一个例外,所以我不能使用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

任何帮助都会非常感激。

感谢大家。

1 个答案:

答案 0 :(得分:0)

我不会使用后台工作者,我自己编写线程。这是我的榜样:

Dim wc As New WebClient

Dim trdMain As New Thread(AddressOf fDownload)

Protected Sub sRun()
    trdMain.IsBackground = True
    trdMain.Start()
End Sub

Protected Function fDownload()  
    ' iterate through and download
    For Each str As String In strImages
        wc.DownloadString(str, "your location")
    Next

    Return True ' terminate the thread
End Function

这意味着您有一系列要下载的图像的URL。然后,您可以轻松地将其实现到您的代码中,简单而有效。