2014-01-15 54 views
0

我構建了一個腳本,通過解析網站列表中的html給我一個產品數組。無法通過解析獲取圖片網址

我認爲,即時通訊做的一切權利。但出於某種原因,我有alots困難的使用DOMXPath檢索元素我只是在一個網站Makita.ca

所以..。我所提供的原始HTML,即時通訊從makita.ca越來越

我想要得到什麼畫面是那些對在左邊

圖片

也請注意,我唯一需要的是鏈接圖像,而不是實際的 圖像。

如下因素圖像頁面是http://www.makita.ca/index2.php?event=tool&id=100enter image description here

$productArray = array(); 
    $Dom = new DOMDocument(); 
    @$Dom -> loadHTML($this->html); 
    $xpath = new DOMXPath($Dom); 
    echo $xpath -> query('//*[@id="content_other"]/table[2]/tbody/tr/td[1]/table/tbody/tr[4]/td/table/tbody/tr[1]/td/div/a/img')->length; 
     if($xpath -> query('//*[@id="content_other"]/table[2]/tbody/tr/td[1]/table/tbody/tr[4]/td/table')->length > 0) 
     { 
      for($i=0;$i<$xpath->query('//*[@id="content_other"]/table[2]/tbody/tr/td[1]/table/tbody/tr[4]/td/table/tbody/tr')->length;$i++) 
      { 
       if($xpath->query('//*[@id="content_other"]/table[2]/tr/td[1]/table/tr[4]/td/table/tr['.$i.']/td/div/a/img') > 0) 
        $productArray['picture'][] = $xpath -> query('//*[@id="content_other"]/table[2]/tr/td[1]/table/tr[4]/td/table/tr['.$i.']/td/div/a/img')->item(0)->nodeValue; 
      } 
     } 

你看到的是我的錯?因爲現在我真的失去了。

編輯:

確定用於測試目的,我正在呼應查詢的length()方法女巫應該給我多少元素匹配查詢

所以我重新輸入到孔查詢下來,他們能夠」 t沒有任何非asci字符 所以我重新打孔查詢'// * [@ id =「content_other」]/table [2] // tr/td 1/table // tr [4]/td/table // tr 1/td/div/a/img' 那麼結果是0

所以我刪除了部分查詢部分的結尾..

//*[@id="content_other"]/table[2]//tr/td[1]/table//tr[4]/td/table//tr[1]/td/div‌​/a = 0 
//*[@id="content_other"]/table[2]//tr/td[1]/table//tr[4]/td/table//tr[1]/td/div‌​ = 0 
//*[@id="content_other"]/table[2]//tr/td[1]/table//tr[4]/td/table//tr[1]/td = 0 
//*[@id="content_other"]/table[2]//tr/td[1]/table//tr[4]/td/table//tr[1] = 0 
//*[@id="content_other"]/table[2]//tr/td[1]/table//tr[4]/td/table = 0 
//*[@id="content_other"]/table[2]//tr/td[1]/table//tr[4]/td = 0 
//*[@id="content_other"]/table[2]//tr/td[1]/table//tr = 5 

Wooo我在這裏得到了一些元素匹配! 好吧,讓我們嘗試的最後一個元素女巫是如此,因爲它是基於零,則獲得TR 5號,我需要爲路徑這

//*[@id="content_other"]/table[2]//tr/td[1]/table//tr[4] 

進入,但我仍然得到0的一個,我需要 ...所以我不知道該怎麼做更多..

+2

這是一個確切的重複,刪除所有'/ tbody'步驟是所有你需要做的。詳情請參考給定的參考。 –

+0

@JensErat嘿謝謝你們。但我刪除了tbody,但仍然無法正常工作。我開始編輯echo $ xpath - > query('// * [@ id =「content_other」]/table [2] // tr/td [1]/table // tr [4]/td/table// TR [1]/TD/DIV /一個/ IMG') - >長度;它回聲0 –

+1

我不知道什麼搞砸了,但最後四個軸步驟中的一個字符是非ascii並打破查詢。嘗試'//* [@ id =「content_other」]/table [2] // tr/td [1]/table // tr [4]/td/table // tr [1]/td/div/a/img'(我重新輸入了這四個步驟)。 –

回答

0

//div[@class='product_heading']/ancestor-or-self::table[1]//a/img首先選擇「動作鏡頭」,然後在該集團下找到的所有圖像。

這個XPath表達式比你的更可靠,因爲位置表達式的數量很少,隨着標記的變化,這些表達式很容易中斷。

//div[@class='product_heading']/ancestor-or-self::table[1]//a[@rel='thumbnail']/img將是一個強大的安全

+0

謝謝!你的第一個xpath工作。我被佔用的xpath不工作,我從來沒有想過用不同的方式重寫它......再次感謝 –

+0

對不起,第二個xpath中出現錯誤的「@」字符 – Grooveek