2014-03-30 114 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