4

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

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

4

3 回答 3

8

假设您要检索 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());
        }
    }
}
于 2008-12-22T13:01:37.433 回答
5

对于 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();
于 2008-12-22T17:04:05.633 回答
0

it's not the most obvious (and the best) way but i found out that in windows forms you can use WebBrowser control (if you actually need it), fill it's Url property with the url you need and when it's loaded, read the DocumentText property - it contains the html code of the viewed site.

于 2008-12-23T09:11:52.140 回答