[使用C#访问网页的内容

问题描述 投票:5回答:7

我正在尝试使用C#访问网页的内容。例如,我要获取Google主页正文的文本。

我知道这在C#中可以通过其Web浏览器控件来完成。但是我找不到一个很好的,简单的例子。我在网上找到的所有资源都涉及创建Forms和GUI,这些都是我不需要的,我只需要一个好的旧控制台应用程序。

如果任何人都可以提供完成上述任务的基于控制台的简单代码片段,将不胜感激。

c# .net dom
7个回答
14
投票

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

1
投票

如果只需要内容而不是实际的浏览器,则可以使用HttpWebRequest。

这里是代码示例: http://www.c-sharpcorner.com/Forums/ShowMessages.aspx?ThreadID=58261


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 ); 

上面的代码显示了《魔兽世界》的维护消息(如果已发布任何消息)


1
投票

您还可以使用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();
        }
      }
    } 

0
投票

HTML Agility Pack可能就是您需要的。它提供了通过DOM和XPath对HTML页面的访问。


0
投票

Google屏幕抓取,如上所述,使用HttpWebRequest。当您做任何事情时,我建议您使用Fiddler来帮助您了解实际情况。


0
投票

已经十年了,Microsoft不再推荐WebClient用于原始接受答案中指定的新开发。当前的建议是使用System.Net.Http命名空间中的Httpclient。

[https://docs.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);
  }
}`
© www.soinside.com 2019 - 2024. All rights reserved.