2009-07-14 79 views
5

我想用C#访问网页内容的内容。例如,我想抓取google主页正文的文字。访问网页的用C#

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

如果任何人都可以提供一个简单的基于控制台的代码段实现上述,它会不胜感激。

回答

12

其实web浏览器是你希望显示一个网页(嵌入在Windows应用程序管理Internet Explorer)的情况下使用的GUI控制。如果你只需要得到一个网页的内容,你可以使用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

这将无法正常工作? – Saobi 2009-07-14 14:27:24

+0

+1很好完成。 – 2009-07-14 14:27:34

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

您还可以使用华廷库加载和轻松操作网页。这被设计为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

谷歌的屏幕抓取和上面提到的使用HttpWebRequest。当你做你正在做的事时,我建议使用Fiddler来帮助你弄清楚到底发生了什么。如果该网站在JavaScript动态生成(即,如果HTML源代码只是.js文件),右