2009-07-14 76 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文件),右