簡體   English   中英

如何使用簡單HTML DOM解析器從頁面獲取元素

[英]How to get elements from a page using Simple HTML DOM Parser

我正在嘗試使用簡單HTML DOM解析器解析HTML頁面。 該HTML頁面未使用ID,因此很難引用元素。

在此頁面上,我試圖獲取專輯名稱,歌曲標題,下載鏈接和專輯圖像。 我已經做到了,但是我什至無法獲得專輯名稱!

    $html = file_get_html('http://music.banadir24.com/singer/aasha_abdoo/247.html');

    $article = $html->find('table td[class=title]', 0);

    foreach($article as $link){

       echo $link;

    }

輸出: 1tdArrayArrayArray Artist Array

我需要得到這種輸出:

Image Path
Duniya Jamiila [URL]
Macaan Badnoo  [URL]
Donimaayee     [URL]
...

謝謝大家的幫助

請注意:這是合法的,因為歌曲不受版權限制,可以免費下載,只是我需要下載很多歌曲,而且我不能整天坐在那里單擊按鈕。 話雖如此,我花了一個小時才走到這一步。

這是您的意思嗎?

$urls = $html->find('table[width=100%] table tr');
foreach($urls as $url){

   echo $url->children(2);
   echo $url->children(6)->children(0)->href;
   echo '<br>';
}

編輯

使用簡單的HTML DOM

根據您的評論,這里是一些具有一些(希望)有用評論的更新代碼。

$urls = $html->find('table[width=100%] table tr');
foreach($urls as $url){
    // Check that we actually have the right number of children, this was what was breaking before
    if ($url->children(6)) {
        /* Without the following check, we get a digg icon and a useless link. You can merge this with the if statement above, I only have it
         * seperated so that I can write this comment and it will make more sense when reading it for the first time.
         */
        if ($url->children(2)->children(0)->src == 'images/digg.png' || $url->children(2)->children(0)->href == 'javascript:void(0)') continue;
        // echo out the name of the artist. You can get the text without the link by using $url->children(2)->plaintext
        echo $url->children(2);
        // echo out the link. Obviously you could put this href inside a <a href="code-here">whatever-here</a> tag to make the links clickable.
        echo $url->children(6)->children(0)->href;
        echo '<br>'; // just for readability
   }
}

您在示例中使用的頁面上只有三個TD標簽,它們的class屬性值為“ title”。

1. <td height="35" class="title" style="padding-left:7px;"> Artist</td> 
2. <td colspan="3" height="35" class="title" style="padding-left:7px;"><img src="images/b24/dot_next.png" />Desco</td> 
3. <td colspan="3" height="35" class="title" style="padding-left:7px;"><img src="images/b24/dot_next.png" />The Best Of Aasha</td>

第一個總是包含文本“ Artist”,而第二個總是專輯的標題。 它們也是具有class =“ title”和colspan =“ 3”的唯一TD標簽,因此使用HTML DOM解析器選擇它們應該非常容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM