2012-06-08 20 views
0

我試圖製作一個應用程序,用於從網頁下載所有的mp3,但我並沒有從源代碼中下載它們。我從http://ytcracker.com/music/下載併爲每首歌曲列出,如果你複製並粘貼到URL的末尾,它會出現該歌曲的鏈接。我使用的是Web客戶端下載的文件,如果我能在網頁上而不是HTML的ReadLine,然後我可以做client.DownloadFile(url + line, path)這裏是我的代碼:從網頁中讀取文本,而不是HTML

var url = "http://ytcracker.com/music/"; 
var sr = new StreamReader(WebRequest.Create(url).GetResponse().GetResponseStream()); 
string line; 
while ((line = sr.ReadLine()) != null) 
{ 
    MessageBox.Show("http://www.ytcracker.com/music/" + line); 
    using (var client = new WebClient()) 
    { 
     client.DownloadFile("http://www.ytcracker.com/music/" + line, @"C:\Users\Lavi\Downloads\downloadto\.mp3"); 
    } 
} 

問題是「行」獲取的來源該頁面,而不是文字。如果有任何方法可以獲得該頁面的文本,請幫助我。謝謝!

編輯:此外,路徑是,我知道它說'.mp3'而不是文件名,然後.mp3。我將創建一個for循環,並在每次循環時將其添加到列表中,直到頁面全部被讀取,然後將它們添加到.mp3。所以它會像'i.mp3'一樣,所以mp3會在1.mp3,2.mp3,3.mp3等文件夾中。

+0

您不需要以「C#」作爲標題的前綴。 \t 請參閱「[堆棧溢出不需要你的SEO技巧](http://meta.stackexchange.com/a/130208)」。 –

回答

0

您可以使用正則表達式。嘗試了這一點,這是你的代碼 - 我只是添加正則表達式:

var url = "http://ytcracker.com/music/"; 
var sr = new StreamReader(WebRequest.Create(url).GetResponse().GetResponseStream()); 
string line; 

var re = new Regex(@"<li><a href=.*mp3.>(.*)</a></li>"); 

while ((line = sr.ReadLine()) != null) 
{ 
    using (var client = new WebClient()) 
    { 
     if (re.IsMatch(line)) 
     { 
      var match = re.Match(line); 

      client.DownloadFile("http://www.ytcracker.com/music/" + match.Groups[1], @"C:\Users\Lavi\Downloads\downloadto\.mp3"); 
     } 
    } 
} 
+0

與流行的觀點相反,正則表達式並不總是最好的解決方案:-)如果他所刮的頁面發生了大幅度的變化,該怎麼辦?使用完整的HTML解析器調整代碼比改變正則表達式要容易得多。 –

+0

同意。正則表達式是一種解決方案,而不是最好的解決方案。 –

2

你的情況,下載音樂,你將需要閱讀的HREF值,並確保它們是構建路徑之前.mp3文件。正如Eric J所說的,HtmlAgilityPack更易於使用。 只需下載並將dll引用添加到您的項目,然後使用此代碼。

 var url = "http://ytcracker.com/music/"; 
     var sr = new StreamReader(WebRequest.Create(url).GetResponse().GetResponseStream()); 
     HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument(); 
     htmlDoc.LoadHtml(sr.ReadToEnd()); 
     foreach (HtmlNode link in htmlDoc.DocumentNode.SelectNodes("//a[@href]")) 
     { 
      HtmlAttribute att = link.Attributes["href"]; 
      if (att.Value.EndsWith(".mp3")) 
      { 
       MessageBox.Show("http://www.ytcracker.com/music/" + att.Value); 
       using (var client = new WebClient()) 
       { 
        client.DownloadFile("http://www.ytcracker.com/music/" + att.Value, @"C:\Users\Lavi\Downloads\downloadto\.mp3"); 
       } 
      } 
     } 
相關問題