1

我正在尝试抓取一些网站。它就像一个魅力。但是有一个大问题。在某些页面(不是 mutch)上,我得到了一些奇怪的字符而不是 html 代码。

它看起来像这样:

;�<cS���u�/�qYa$�4l7�.�Q�7&��O����� Z�D}z��/���� ��u����V���lWY|�n5�1�We����GB�U��g{�� �|Ϸ����*�Q��0���nb�o�߯�����[b��/����@CƑ����D{{/n��X�!� �Et�X"����?��˩����8\y��&

如果我在浏览器中打开它,完全没有问题。我不明白为什么。

我的 HTTP 标头说:

Accept:text/html,application/xhtml+xml,application/xml;q=0.9, / ;q=0.8 Accept-Encoding:gzip,deflate,sdch Accept-Language:de-DE,de;q=0.8,en- US;q=0.6,en;q=0.4 Cache-Control:max-age=0 Connection:keep-alive User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ 29.0.1547.66 Safari/537.36

我认为这与接受有关

request.Accept = "*/*"

那是我的网络请求:

Public Class Http
    Dim cookieCon As New CookieContainer
    Dim request As HttpWebRequest
    Dim response As HttpWebResponse

    Public Function GetRequest(ByVal Params() As Object)
        Dim url As String = Params(0)
        Dim mycookie As String = Params(1)
        'request.AllowAutoRedirect = True
        request = CType(HttpWebRequest.Create(url), HttpWebRequest)
        request.CookieContainer = New CookieContainer()
        request.Method = "GET"
        request.Timeout = 20000
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36"
        'request.ContentType = "application/x-www-form-urlencoded"
        request.Accept = "*/*"
        If Not mycookie Like "nocookie" Then
            request.Headers("Cookie") = mycookie
        End If
        response = CType(request.GetResponse(), HttpWebResponse)
        Dim html(1) As String
        html(0) = request.Address.ToString()
        html(1) = New StreamReader(response.GetResponseStream()).ReadToEnd()

        Return html
    End Function

谢谢。

4

1 回答 1

1

您下载的数据是 GZip 压缩的。你需要解压它。将您的功能更改为:

 Dim request As HttpWebRequest
Dim response As HttpWebResponse
Public Function GetRequest(ByVal Params() As Object) As String()
    Dim url As String = Params(0)
    Dim mycookie As String = Params(1)
    'request.AllowAutoRedirect = True
    request = CType(HttpWebRequest.Create(url), HttpWebRequest)
    request.CookieContainer = New CookieContainer()
    If Not mycookie Like "nocookie" Then
        request.Headers("Cookie") = mycookie
    End If
    request.AutomaticDecompression = DecompressionMethods.GZip
    response = CType(request.GetResponse(), HttpWebResponse)

    Dim html(1) As String
    html(0) = request.Address.ToString()
    html(1) = New StreamReader(response.GetResponseStream).ReadToEnd()

    Return html
End Function

用法

Dim params(1) As Object
params(0) = url

Dim page As String = GetRequest(params)(1)
于 2013-09-11T18:05:00.530 回答