使用C#访问网页内容

6
我希望使用C#访问网页内容,例如,我想要获取Google主页正文的文本。我知道可以通过C#的Web浏览器控件实现这一点,但我找不到一个好的、简单的示例。我在网上找到的所有资源都涉及创建窗体和GUI,而我不需要这样做,我只需要一个好用的控制台应用程序。如果有人能提供一个简单的基于控制台的代码片段来实现上述功能,将不胜感激。
7个回答

15

实际上,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);
        }
    }
}

3
如果网站是通过JavaScript动态生成的(即HTML源代码仅为.js文件),这种方法就行不通了,对吗? - Saobi
1
@Saobi,你是正确的,使用这种技术不会执行JavaScript。你只能获得网页的纯文本表示。 - Darin Dimitrov
2
我基本上想向一个网站发送查询并获取返回的结果,但该网站全部使用JavaScript编写,因此像Google一样解析HTML源代码是无法帮助的。我应该如何:1)在不知道请求URL的情况下发送查询 2)解析JavaScript生成的页面内容?我需要模拟按键并将其发送吗? - Saobi
无论是否使用Javascript,我仍然认为这是正确的方法。如果这意味着你需要理解Javascript的工作原理,以便自己进行转换,那就这样吧。 - Joel Coehoorn
@Darin:如何处理动态生成的元素?有什么想法吗? - SivaRajini
@Saobi,我也遇到了同样的问题。经过广泛的研究,似乎没有办法在Web请求中执行JavaScript... - Zameer Ansari

2
您还可以使用WatiN库轻松加载和操作网页。这是为Web UI的测试库而设计的。要使用它,请从官方网站http://watin.sourceforge.net/获取最新版本。对于C#,在控制台应用程序中使用以下代码将给您Google首页的HTML(这是从WatiN网站上的入门示例进行修改的)。该库还包含许多有用的方法,可用于获取和设置页面的各个部分,执行操作并检查结果。
   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();
        }
      }
    } 

1
你可以像这样做:
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美国服务器的维护信息(如果有任何信息已发布)


1

但这并没有提供完整的内容,这里指的是JavaScript。 - Zameer Ansari

0

HTML Agility Pack 可能是您所需的工具,它通过 DOM 和 XPath 提供对 HTML 页面的访问。


0

使用 Google 屏幕抓取并像上面提到的那样使用 HttpWebRequest。当您执行任何操作时,我建议使用 Fiddler 帮助您弄清楚发生了什么。


0

已经过去了十年,微软不再推荐使用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);
  }
}`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接