0

我正在使用以下内容获取网页:

Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
request.CookieContainer = logincookie
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(response.GetResponseStream())
Dim thesource As String = reader.ReadToEnd

我正在尝试从源中提取数据。thesource成功保存了页面的源代码,但是,我无法使用 For Each 循环遍历每一行,因为它仅响应每个字符而不是每一行。

有人可以建议如何解决这个问题吗?谢谢大家,斯坦。

4

1 回答 1

1

我看到三个选项。

选项 1. 在 While 循环中逐行读取,而不是 For Each。如果一切都将在同一个函数中,请使用它。

Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
request.CookieContainer = logincookie
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(response.GetResponseStream())
Dim line As String = reader.ReadLine()

While line IsNot Nothing

    'Contents of your For Each loop go here

    line = reader.ReadLine()
End While

选项 2:您至少拥有 Visual Studio 2012 并希望从此函数返回结果,以便可以在调用此代码的代码中使用 For Each 循环。

Public Iterator Function GetUrl(ByVal url As String) As IEnumerable(Of String)

    Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
    request.CookieContainer = logincookie
    Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
    Dim reader As New StreamReader(response.GetResponseStream())
    Dim line As String = reader.ReadLine()

    While line IsNot Nothing

        Yield line
        line = reader.ReadLine()
    End While
End Function

像这样称呼它:

For Each line As String In GetUrl("http://example.com")
    '...
Next line

选项 3:您想从函数返回,就像上一个选项一样,但您不能使用新的迭代器语言功能。

Public Sub GetUrl(ByVal url As String, ByVal lineAction As Action(Of String))

    Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
    request.CookieContainer = logincookie
    Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
    Dim reader As New StreamReader(response.GetResponseStream())
    Dim line As String = reader.ReadLine()

    While line IsNot Nothing
        lineAction(line)
        line = reader.ReadLine()
    End While
End Sub

像这样称呼它:

GetUrl("http://example.com", _
   Sub(l)
       'Do stuff here
   End Sub)
于 2013-02-01T02:58:07.563 回答