我希望使用C#访问网页内容,例如,我想要获取Google主页正文的文本。我知道可以通过C#的Web浏览器控件实现这一点,但我找不到一个好的、简单的示例。我在网上找到的所有资源都涉及创建窗体和GUI,而我不需要这样做,我只需要一个好用的控制台应用程序。如果有人能提供一个简单的基于控制台的代码片段来实现上述功能,将不胜感激。
实际上,WebBrowser是一个GUI控件,用于在Windows应用程序中嵌入和管理Internet Explorer以可视化网页。如果您只需要获取网页的内容,您可以使用WebClient类:
class Program
{
static void Main(string[] args)
{
using (var client = new WebClient())
{
var contents = client.DownloadString("http://www.google.com");
Console.WriteLine(contents);
}
}
}
using System;
using WatiN.Core;
namespace Test
{
class WatiNConsoleExample
{
[STAThread]
static void Main(string[] args)
{
// Open an new Internet Explorer Window and
// goto the google website.
IE ie = new IE("http://www.google.com");
// Write out the HTML text of the body
Console.WriteLine(ie.Text);
// Close Internet Explorer and the console window immediately.
ie.Close();
Console.Readkey();
}
}
}
Uri u = new Uri( @"http://launcher.worldofwarcraft.com/alert" );
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(u);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
System.IO.Stream st = res.GetResponseStream();
System.IO.StreamReader sr = new System.IO.StreamReader(st);
string body = sr.ReadToEnd();
System.Console.WriteLine( "{0}", body );
以上代码显示WoW美国服务器的维护信息(如果有任何信息已发布)
使用 Google 屏幕抓取并像上面提到的那样使用 HttpWebRequest。当您执行任何操作时,我建议使用 Fiddler 帮助您弄清楚发生了什么。
已经过去了十年,微软不再推荐使用WebClient进行新开发,正如原始接受的答案所指定的那样。当前的建议是使用System.Net.Http命名空间中的HttpClient。
来自https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netcore-3.1的当前示例为:
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method below
// string responseBody = await client.GetStringAsync(uri);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}`