我是否可以从www.google.com网站背后的一些c#代码中获得网站的源代码(最好是字符串),比如asp.net?
编辑:当然,我指的是html代码--在每个浏览器中,您都可以使用上下文菜单中的“查看源代码”来查看它。
发布于 2008-12-22 05:01:37
假设您想检索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-22 09:04:05
对于C#,我更喜欢使用HttpWebRequest over WebClient,因为将来您可以有更多的选项,比如GET/POST参数,使用Cookies等等。
您可以在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-23 01:11:52
这并不是最明显(也是最好的)方式,但我发现在windows表单中,您可以使用WebBrowser控件(如果您确实需要它),用您需要的Url填充它的url属性,当它加载时,读取DocumentText属性-它包含查看站点的html代码。
https://stackoverflow.com/questions/386189
复制