【问题标题】:Get the source of some website from asp.net code从asp.net代码中获取某个网站的源码
【发布时间】:2009-04-14 17:00:10
【问题描述】:

有什么方法可以让我从 asp.net 网站后面的代码中的一些 c# 代码中获取网站的来源(最好是字符串),比如 www.google.com?

编辑:当然我的意思是 html 代码 - 在每个浏览器中,您都可以使用上下文菜单中的“查看 source”来查看它。

【问题讨论】:

  • 请说清楚...您是要获取网站的源代码还是要获取网站的 HTML 内容并自己在 C# 中解析?

标签: c# asp.net-2.0


【解决方案1】:

假设您要检索 html:

class Program
{
    static void Main(string[] args)
    {
        using (WebClient client = new WebClient())
        using (Stream stream = client.OpenRead("http://www.google.com"))
        using (StreamReader reader = new StreamReader(stream))
        {
            Console.WriteLine(reader.ReadToEnd());
        }
    }
}

【讨论】:

    【解决方案2】:

    对于 C#,我更喜欢使用 HttpWebRequest 而不是 WebClient,因为您将来可以有更多选择,例如使用 GET/POST 参数、使用 Cookie 等。

    您可以在MSDN 获得最短的解释。

    这是来自 MSDN 的示例:

            // Create a new HttpWebRequest object.
            HttpWebRequest request=(HttpWebRequest) WebRequest.Create("http://www.contoso.com/example.aspx");    
    
            // Set the ContentType property. 
            request.ContentType="application/x-www-form-urlencoded";
            // Set the Method property to 'POST' to post data to the URI.
            request.Method = "POST";
            // Start the asynchronous operation.    
            request.BeginGetRequestStream(new AsyncCallback(ReadCallback), request);    
    
            // Keep the main thread from continuing while the asynchronous
            // operation completes. A real world application
            // could do something useful such as updating its user interface. 
            allDone.WaitOne();
    
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse);
            string responseString = streamRead.ReadToEnd();
            Console.WriteLine(responseString);
            // Close the stream object.
            streamResponse.Close();
            streamRead.Close();
    
            // Release the HttpWebResponse.
            response.Close();
    

    【讨论】:

      【解决方案3】:

      这不是最明显(也是最好)的方式,但我发现在 Windows 窗体中你可以使用 WebBrowser 控件(如果你真的需要它),用你需要的 url 填充它的 Url 属性,当它加载时,阅读DocumentText 属性 - 它包含所查看站点的 html 代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-24
        • 2018-01-29
        • 1970-01-01
        • 1970-01-01
        • 2012-11-28
        • 2023-02-14
        • 1970-01-01
        • 2012-06-23
        相关资源
        最近更新 更多