有沒有什麼辦法可以從一些c#代碼後面的代碼中獲得一個網站的源代碼(最好是字符串),讓我們說www.google.com。 asp.net網站?從asp.net代碼獲取一些網站的源代碼
編輯:當然我的意思是html代碼 - 在每個瀏覽器中,您可以在上下文菜單中使用「查看源」查看它。
有沒有什麼辦法可以從一些c#代碼後面的代碼中獲得一個網站的源代碼(最好是字符串),讓我們說www.google.com。 asp.net網站?從asp.net代碼獲取一些網站的源代碼
編輯:當然我的意思是html代碼 - 在每個瀏覽器中,您可以在上下文菜單中使用「查看源」查看它。
假設你要檢索的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());
}
}
}
對於C#,我更喜歡使用HttpWebRequest在Web客戶端,因爲你可以有像有GET/POST參數,用餅乾等未來更多的選擇
您可以在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();
它不是最明顯的(和最好)的方式,但我發現,在Windows窗體中您可以使用WebBrowser控件(如果你確實需要它)用你需要的URL填充它的Url屬性,當它被加載時,閱讀DocumentText屬性 - 它包含被查看網站的html代碼。
請說清楚...你想獲得網站的源代碼,或者你想獲取一個網站的HTML內容,並在C#中自己解析它? – Tom 2008-12-22 12:52:27