2010-04-09 90 views
0

我想從以下網站刮一些東西:http://www.conrad.nl/modelspoor用c#抓取JavaScript cookie的網站#

這是我的函數:

public string SreenScrape(string urlBase, string urlPath) 
{ 
    CookieContainer cookieContainer = new CookieContainer(); 
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(urlBase + urlPath); 
    httpWebRequest.CookieContainer = cookieContainer; 
    httpWebRequest.UserAgent = "Mozilla/6.0 (Windows; U; Windows NT 7.0; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.9 (.NET CLR 3.5.30729)"; 
    WebResponse webResponse = httpWebRequest.GetResponse(); 
    string result = new System.IO.StreamReader(webResponse.GetResponseStream(), Encoding.Default).ReadToEnd(); 
    webResponse.Close(); 

    if (result.Contains("<frame src=")) 
    { 
     Regex metaregex = new Regex("http:[a-z:/._0-9!?=A-Z&]*",RegexOptions.Multiline); 
     result = result.Replace("\r\n", ""); 
     Match m = metaregex.Match(result); 
     string key = m.Groups[0].Value; 

     foreach (Match match in metaregex.Matches(result)) 
     { 
      HttpWebRequest redirectHttpWebRequest = (HttpWebRequest)WebRequest.Create(key); 
      redirectHttpWebRequest.CookieContainer = cookieContainer; 
      webResponse = redirectHttpWebRequest.GetResponse(); 
      string redirectResponse = new System.IO.StreamReader(webResponse.GetResponseStream(), Encoding.Default).ReadToEnd(); 
      webResponse.Close(); 
      return redirectResponse; 
     } 

    } 
    return result; 
} 

但是,當我這樣做,我得到與它使用JavaScript的網站錯誤的字符串。

是否有人知道如何解決這一問題?

+0

注意到你不設置redirectHttpWebRequest.UserAgent爲您HttpWebRequest的主要求做。也許它會導致問題? – 2010-04-11 01:09:14

回答

0

使用我博客上的文章(Use C# to Scrape web pages)我能夠獲得該頁面。下面是代碼:

string target   = @"http://www1.conrad.nl/modelspoor/"; 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(target); 
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

using (Stream responseStream = response.GetResponseStream()) 
    using (StreamReader htmlStream = new StreamReader(responseStream, Encoding.UTF8)) 
     Console.WriteLine(htmlStream.ReadToEnd()); 

HTH

+0

嗨, 對不起,我忘了電話,我從第一頁得到的HTML。我有一個幀索引。 當我去框架鏈接,我得到關於JavaScript的錯誤或不能創建一個shopchart。 我想從底部中間屏幕中的菜單項。 – erwin 2010-04-09 21:01:55

+0

我的不好...抱歉。 – OmegaMan 2010-04-09 21:05:32

+0

你有一個想法如何解決它? – erwin 2010-04-09 21:16:10