超长网页的地址:
http://club.autohome.com.cn/bbs/thread-c-813-4881481-1.html哪位大侠可以提供一份代码给我,可以成功的获取上面地址的html代码,谢谢。
试过很多HttpWebRequest写的代码,但是没有一个管用,程序运行几分钟之后,最终报错:操作已经超时。
但是用IE浏览器却可以正常打开。

解决方案 »

  1.   


    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.IO;namespace ConsoleApplication5
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.Write(getHtml("http://club.autohome.com.cn/bbs/thread-c-813-4881481-1.html"));
                Console.Read();        }
            protected static string getHtml(string url)
            {
                string html = "";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Accept = "*/*";
                HttpWebResponse response = null;
                Stream stream = null;
                StreamReader reader = null;
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                    stream = response.GetResponseStream();
                    reader = new StreamReader(stream, Encoding.UTF8);
                    html = reader.ReadToEnd().Replace("\r\n", "");   //我知道这里会改变html代码,但和这里没关系
                }/*
                catch (Exception excpt)
                {
                    Console.WriteLine(excpt);
                    Console.Write("\n【注意】出现异常,输入任意字符和回车继续:");
                    Console.ReadLine();
                }*/
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                        reader.Dispose();
                    }
                    if (stream != null)
                    {
                        stream.Close();
                        stream.Dispose();
                    }
                    if (response != null)
                    {
                        response.Close();
                    }
                }
                return html;
            }
        }
    }
      

  2.   

    try.../// <summary>
    /// 通过URL取网页源代码
    /// </summary>
    /// <param name="url">URL</param>
    /// <param name="encoding">网页编码</param>
    /// <returns></returns>
    private string GetHtmlCode(string url, Encoding encoding)
    {
        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
        System.Net.WebResponse response = request.GetResponse();
        System.IO.Stream resStream = response.GetResponseStream();
        System.IO.StreamReader sr = new System.IO.StreamReader(resStream, encoding);
        string html = (sr.ReadToEnd());
        resStream.Close();
        sr.Close();
        return html;
    }
    //调用
    richTextBox2.Text = GetHtmlCode(@"http://club.autohome.com.cn/bbs/thread-c-813-4881481-1.html", Encoding.GetEncoding("gb2312"));
      

  3.   


    reader = new StreamReader(stream, Encoding.GetEncoding("GB2312"));//因为你那个网页的编码格式为GB2312 改下这里
      

  4.   

    static string GetPage(string url) 
      { 
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); 
        try 
        { 
          using (HttpWebResponse res = (HttpWebResponse)req.GetResponse()) 
          { 
            using (StreamReader sr = new StreamReader(res.GetResponseStream())) 
            { 
              return sr.ReadToEnd(); 
            } 
          } 
        } 
        catch (System.Exception e) 
        { 
          return e.Message; 
        } 
        finally 
        { 
          req.Abort(); 
        } 
      } 
    byte[] data = encoding.GetBytes(""); 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(""); 
    Stream writer = request.GetRequestStream(); 
            writer.Write(data, 0, data.Length); 
            writer.Flush(); 
            writer.Close(); 
            HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
            Stream stream = response.GetResponseStream(); 
            StreamReader reader = new StreamReader(stream, encoding); 
            string html = reader.ReadToEnd(); 
      

  5.   

    抓去特定内容,分批抓取
    http://topic.csdn.net/u/20090507/19/d128076e-7636-4529-a807-420189853fab.html
      

  6.   


                System.Net.WebClient wc = new System.Net.WebClient();
                string content = wc.DownloadString("http://club.autohome.com.cn/bbs/thread-c-813-4881481-1.html");
                Console.WriteLine(content);
      

  7.   

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://club.autohome.com.cn/bbs/thread-c-813-4881481-1.html");
                request.Method = "post";
                request.Accept = "*/*";
                request.ContentLength = 0;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.00; Windows NT)";
                Stream sm = request.GetResponse().GetResponseStream();
                StreamReader sr = new StreamReader(sm, System.Text.Encoding.GetEncoding("gb2312"));
                string s = sr.ReadToEnd();
                sm.Close();
            
                Console.WriteLine(s);//标红色的这行是关键,那网站防止其他工具抓取他站点内容,通过useragent来判断浏览器是否是ie/ff等常用浏览器,你这里模拟下ie就好了。
      

  8.   

    to zengfanxing , lxcnn , ojlovecd , wjq :
    测试了你们的代码,但是结果还是一样,报错: 操作已超时。to wuyq11 :
    抓去特定内容,分批抓取  ,应该怎样操作,有没有代码?
    你给的那个地址看过了,是说聚合百度和google的搜索结果的吧。
      

  9.   

    未处理的“System.Net.WebException”类型的异常出现在 System.dll 中。其他信息: 操作已超时。>>> string content = wc.DownloadString("http://club.autohome.com.cn/bbs/thread-c-813-4881481-1.html");
      

  10.   

    局部变量:
    ------------
    - $exception {"操作已超时。"} System.Exception {System.Net.WebException}
    - [System.Net.WebException] {"操作已超时。"} System.Net.WebException
    - base {"操作已超时。"} System.InvalidOperationException {System.Net.WebException}
    - base {"操作已超时。"} System.SystemException {System.Net.WebException}
    - base {"操作已超时。"} System.Exception {System.Net.WebException}
    _className 有关包含类的信息不可用,因此无法获取字段“_className”的值。 string
    _data 有关包含类的信息不可用,因此无法获取字段“_data”的值。 System.Collections.IDictionary
    _dynamicMethods 有关包含类的信息不可用,因此无法获取字段“_dynamicMethods”的值。 object
    _exceptionMethod 有关包含类的信息不可用,因此无法获取字段“_exceptionMethod”的值。 System.Reflection.MethodBase
    _exceptionMethodString 有关包含类的信息不可用,因此无法获取字段“_exceptionMethodString”的值。 string
    _helpURL 有关包含类的信息不可用,因此无法获取字段“_helpURL”的值。 string
    _HResult 有关包含类的信息不可用,因此无法获取字段“_HResult”的值。 int
    _innerException 有关包含类的信息不可用,因此无法获取字段“_innerException”的值。 System.Exception
    _message 有关包含类的信息不可用,因此无法获取字段“_message”的值。 string
    _remoteStackIndex 有关包含类的信息不可用,因此无法获取字段“_remoteStackIndex”的值。 int
    _remoteStackTraceString 有关包含类的信息不可用,因此无法获取字段“_remoteStackTraceString”的值。 string
    _source 有关包含类的信息不可用,因此无法获取字段“_source”的值。 string
    _stackTrace 有关包含类的信息不可用,因此无法获取字段“_stackTrace”的值。 object
    _stackTraceString 有关包含类的信息不可用,因此无法获取字段“_stackTraceString”的值。 string
    _xcode 有关包含类的信息不可用,因此无法获取字段“_xcode”的值。 int
    _xptrs 有关包含类的信息不可用,因此无法获取字段“_xptrs”的值。 System.IntPtr
    + Data {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
    HelpLink null string
    HResult -2146233079 int
    + InnerException null System.Exception
    IsTransient false bool
    Message "操作已超时。" string
    Source "System" string
    StackTrace "   在 System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)\r\n   在 System.Net.WebClient.DownloadString(Uri address)\r\n   在 System.Net.WebClient.DownloadString(String address)\r\n   在 HttpWebRequest_Test.Form1.button1_Click(Object sender, EventArgs e) 位置 F:\\Work\\Code\\C#\\HttpWebRequest_Test\\HttpWebRequest_Test\\Form1.cs:行号 86\r\n   在 System.Windows.Forms.Control.OnClick(EventArgs e)\r\n   在 System.Windows.Forms.Button.OnClick(EventArgs e)\r\n   在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)\r\n   在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)\r\n   在 System.Windows.Forms.Control.WndProc(Message& m)\r\n   在 System.Windows.Forms.ButtonBase.WndProc(Message& m)\r\n   在 System.Windows.Forms.Button.WndProc(Message& m)\r\n   在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)\r\n   在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)\r\n   在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)\r\n   在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)\r\n   在 System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)\r\n   在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)\r\n   在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)\r\n   在 System.Windows.Forms.Application.Run(Form mainForm)\r\n   在 HttpWebRequest_Test.Program.Main() 位置 F:\\Work\\Code\\C#\\HttpWebRequest_Test\\HttpWebRequest_Test\\Program.cs:行号 17" string
    + TargetSite {Byte[] DownloadDataInternal(System.Uri, System.Net.WebRequest ByRef)} System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}
    + 静态成员
    InternalStatus RequestFatal System.Net.WebExceptionInternalStatus
    m_InternalStatus 有关包含类的信息不可用,因此无法获取字段“m_InternalStatus”的值。 System.Net.WebExceptionInternalStatus
    m_Response 有关包含类的信息不可用,因此无法获取字段“m_Response”的值。 System.Net.WebResponse
    m_Status 有关包含类的信息不可用,因此无法获取字段“m_Status”的值。 System.Net.WebExceptionStatus
    Response null System.Net.WebResponse
    Status Timeout System.Net.WebExceptionStatus
    _className 有关包含类的信息不可用,因此无法获取字段“_className”的值。 string
    _data 有关包含类的信息不可用,因此无法获取字段“_data”的值。 System.Collections.IDictionary
    _dynamicMethods 有关包含类的信息不可用,因此无法获取字段“_dynamicMethods”的值。 object
    _exceptionMethod 有关包含类的信息不可用,因此无法获取字段“_exceptionMethod”的值。 System.Reflection.MethodBase
    _exceptionMethodString 有关包含类的信息不可用,因此无法获取字段“_exceptionMethodString”的值。 string
    _helpURL 有关包含类的信息不可用,因此无法获取字段“_helpURL”的值。 string
    _HResult 有关包含类的信息不可用,因此无法获取字段“_HResult”的值。 int
    _innerException 有关包含类的信息不可用,因此无法获取字段“_innerException”的值。 System.Exception
    _message 有关包含类的信息不可用,因此无法获取字段“_message”的值。 string
    _remoteStackIndex 有关包含类的信息不可用,因此无法获取字段“_remoteStackIndex”的值。 int
    _remoteStackTraceString 有关包含类的信息不可用,因此无法获取字段“_remoteStackTraceString”的值。 string
    _source 有关包含类的信息不可用,因此无法获取字段“_source”的值。 string
    _stackTrace 有关包含类的信息不可用,因此无法获取字段“_stackTrace”的值。 object
    _stackTraceString 有关包含类的信息不可用,因此无法获取字段“_stackTraceString”的值。 string
    _xcode 有关包含类的信息不可用,因此无法获取字段“_xcode”的值。 int
    _xptrs 有关包含类的信息不可用,因此无法获取字段“_xptrs”的值。 System.IntPtr
    + Data {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
    HelpLink null string
    HResult -2146233079 int
    - InnerException null System.Exception
    - 静态成员
    _COMPlusExceptionCode -532459699 int
    IsTransient false bool
    Message "操作已超时。" string
    Source "System" string
    StackTrace "   在 System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)\r\n   在 System.Net.WebClient.DownloadString(Uri address)\r\n   在 System.Net.WebClient.DownloadString(String address)\r\n   在 HttpWebRequest_Test.Form1.button1_Click(Object sender, EventArgs e) 位置 F:\\Work\\Code\\C#\\HttpWebRequest_Test\\HttpWebRequest_Test\\Form1.cs:行号 86\r\n   在 System.Windows.Forms.Control.OnClick(EventArgs e)\r\n   在 System.Windows.Forms.Button.OnClick(EventArgs e)\r\n   在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)\r\n   在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)\r\n   在 System.Windows.Forms.Control.WndProc(Message& m)\r\n   在 System.Windows.Forms.ButtonBase.WndProc(Message& m)\r\n   在 System.Windows.Forms.Button.WndProc(Message& m)\r\n   在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)\r\n   在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)\r\n   在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)\r\n   在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)\r\n   在 System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)\r\n   在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)\r\n   在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)\r\n   在 System.Windows.Forms.Application.Run(Form mainForm)\r\n   在 HttpWebRequest_Test.Program.Main() 位置 F:\\Work\\Code\\C#\\HttpWebRequest_Test\\HttpWebRequest_Test\\Program.cs:行号 17" string
    + TargetSite {Byte[] DownloadDataInternal(System.Uri, System.Net.WebRequest ByRef)} System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}
    - 静态成员
    _COMPlusExceptionCode -532459699 int
    + this {HttpWebRequest_Test.Form1, Text: Form1} HttpWebRequest_Test.Form1
    + sender {Text = "button1"} object {System.Windows.Forms.Button}
    + e {X = 23 Y = 12 Button = Left} System.EventArgs {System.Windows.Forms.MouseEventArgs}
    + wc {System.Net.WebClient} System.Net.WebClient
    content null string
      

  11.   

    会不会是你之前用完HttpWebResponse的时候没有Close掉呢?你重启一下你的电脑再试试
      

  12.   

    都测试过才给你贴出来的,
    request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.00; Windows NT)"; 
    不加这句就超时,加上就可以了,主要就是网站的防抓取手段。