2014-03-30 59 views
0

我想解析這個htmlpage:http://mp3skull.com/mp3/eminem.html使用WP8的HtmlAgilityPack。 我必須帶着這種風格的所有div:「font-size:15px;」。 我寫這樣的:解析特定的div HtmlAgilityPack

HttpWebRequest httpRequest = (HttpWebRequest)result.AsyncState; 
        WebResponse response = httpRequest.EndGetResponse(result); 

        Stream stream = response.GetResponseStream(); 
        StreamReader reader = new StreamReader(stream); 
        strResponse = reader.ReadToEnd(); 

        HtmlDocument htmlDocument = new HtmlDocument(); 
        htmlDocument.OptionFixNestedTags = true; 
        htmlDocument.LoadHtml(strResponse); 

        if (htmlDocument.DocumentNode != null) 
        { 
         // parsing page's title 
         HtmlAgilityPack.HtmlNode titleNode = htmlDocument.DocumentNode.SelectSingleNode("//title"); 
         if (titleNode != null) 
         { 
          Vista.Title = titleNode.InnerText; 
         } 

         var elements = htmlDocument.DocumentNode.SelectNodes("//div['style=font-size:15px;']"); 

         if (elements != null) 
         { 
          for (int i = 0; i < elements.Count; i++) 
          { 
           risultati.Add(elements[i].InnerHtml.Trim()); 
          } 
          //LLSResult.ItemsSource = risultati; 
          test.Text = risultati.ElementAt(0).ToString(); 
         } 
        } 

標題被印刷,但在 「risultati」(的ObservableCollection)元素不。 此外,應用程序幾秒鐘後關閉他完成工作。

謝謝

回答

0

如果您只是在尋找解析標題的方法。這裏是我的嘗試:

class Program 
{ 
    static void Main(string[] args) 
    { 

     using (var webClient = new WebClient()) 
     { 
      webClient.DownloadStringCompleted+=webClient_DownloadStringCompleted; 
      webClient.DownloadStringAsync(new Uri("http://mp3skull.com/mp3/eminem.html"));   
     } 

     System.Diagnostics.Process.GetCurrentProcess().WaitForExit(); 

    } 

    static void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
    { 
     if (e.Error != null) 
     { 
      Console.WriteLine("Error: {0}", e.Error.Message); 
      return; 
     } 

     var source = e.Result.Trim(); 

     if (string.IsNullOrEmpty(source)) 
     { 
      Console.WriteLine("Page not returned."); 
      return; 
     } 


     foreach (Match match in Regex.Matches(source,"<div style=\"font-size:15px;\"><b>(?<title>.*?)</b></div>")) 
     { 
      Console.WriteLine(match.Groups["title"].Value); 
     } 

    } 
} 
+0

嗨,我的代碼適用於標題,我沒有問題。我的問題是如何使用這個屬性(font-size:15px)帶ALL div。我的代碼在它們上面返回空值 – Krusty

+0

上面的代碼沒有解析頁面標題,而是從ALL div中獲取歌曲名稱(font-size:15px) –

+0

哦對不起。它的工作原理,非常感謝 – Krusty