2010-12-23 81 views
3

我需要编写一个简单的C#应用​​程序,该应用程序应接收当前在Firefox中打开的网页的全部内容。有没有办法直接从C#做到这一点?如果没有,是否有可能开发某种可以传输页面内容的插件?由于我是Firefox插件编程的全新手,我非常感谢让我快速启动的任何信息。也许有一些我可以用作参考的来源?文件链接?建议?从C#程序中获取Firefox中的网页内容

UPD:其实我需要一个Firefox实例进行通信,而不是从给定的URL

+0

我给你第一部分;从C#开始,可以使用以下内容读取网页:http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx。我不知道如何在Firefox中抓取页面。 – 2010-12-23 11:47:16

回答

1

如果您详细说明您试图实现的内容,将会有所帮助。可能是已经在那里的插件,如萤火虫可以帮助。

Anways,如果你真的想同时开发插件和C#应用程序:

看看这个教程Firefox扩展: http://robertnyman.com/2009/01/24/how-to-develop-a-firefox-extension/

否则,您可以使用WebRequest类或HttpWebRequest类在.NET请求获取任何URL的HTML源代码。

0

我想你几乎肯定需要写一个Firefox插件为获得一个网页的内容。然而,当然有办法请求一个网页,并在C#中接收它的HTML响应。这取决于你的要求是什么?

如果您的要求只是从任何网站收到的来源,留下评论,我会指出你的代码。

+0

对不起模糊的问题,我澄清了一下。我需要与Firefox实例进行通信。 – 2010-12-23 11:50:41

+0

在这种情况下,您需要下载Firefox插件路径 – 2010-12-23 11:52:56

0
Uri uri = new Uri(url); 
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri.AbsoluteUri); 
     req.AllowAutoRedirect = true; 
     req.MaximumAutomaticRedirections = 3; 
     //req.UserAgent = _UserAgent; //"Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; Searcharoo.NET)"; 
     req.KeepAlive = true; 
     req.Timeout = _RequestTimeout * 1000; //prefRequestTimeout 

     // SIMONJONES http://codeproject.com/aspnet/spideroo.asp?msg=1421158#xx1421158xx 
     req.CookieContainer = new System.Net.CookieContainer(); 
     req.CookieContainer.Add(_CookieContainer.GetCookies(uri)); 

System.Net.HttpWebResponse webresponse = null;

 try 
     { 
      webresponse = (System.Net.HttpWebResponse)req.GetResponse(); 
     } 
     catch (Exception ex) 
     { 
      webresponse = null; 
      Console.Write("request for url failed: {0} {1}", url, ex.Message); 
     } 

     if (webresponse != null) 
     { 
      webresponse.Cookies = req.CookieContainer.GetCookies(req.RequestUri); 
      // handle cookies (need to do this incase we have any session cookies) 
      foreach (System.Net.Cookie retCookie in webresponse.Cookies) 
      { 
       bool cookieFound = false; 
       foreach (System.Net.Cookie oldCookie in _CookieContainer.GetCookies(uri)) 
       { 
        if (retCookie.Name.Equals(oldCookie.Name)) 
        { 
         oldCookie.Value = retCookie.Value; 
         cookieFound = true; 
        } 
       } 
       if (!cookieFound) 
       { 
        _CookieContainer.Add(retCookie); 
       } 
      } 
string enc = "utf-8"; // default 
      if (webresponse.ContentEncoding != String.Empty) 
      { 
       // Use the HttpHeader Content-Type in preference to the one set in META 
       doc.Encoding = webresponse.ContentEncoding; 
      } 
      else if (doc.Encoding == String.Empty) 
      { 
       doc.Encoding = enc; // default 
      } 
      //http://www.c-sharpcorner.com/Code/2003/Dec/ReadingWebPageSources.asp 
      System.IO.StreamReader stream = new System.IO.StreamReader 
       (webresponse.GetResponseStream(), System.Text.Encoding.GetEncoding(doc.Encoding)); 

webresponse.Close();