2013-04-12 139 views
0

我想從一些HTML中提取多個值,並且我認爲XPath可能是實現此目的的理想方法。使用XPath從HTML獲取多個值

我想這樣做的什麼是通過具有類data則循環中的每個循環tr得到我所需要的數據,是route_numbera內的文本(也在標題)和via文本。

的HTML低於:

<tr class="data"><th class="route_number"><a href="/routes/west-midlands/B001v/?tab=" title="Dudley - Sedgley - Wolverhampton - Tettenhall Wood"><span class="route_number small_curvy">1</span></a></th> 
    <td class="main_and_via"> 
    <a href="/routes/west-midlands/B001v/?tab=" title="Dudley - Sedgley - Wolverhampton - Tettenhall Wood">Dudley - Sedgley - Wolverhampton - Tettenhall Wood</a> 
      <span class="via"><strong>via</strong> Dudley Road and Tettenhall Road</span> 
      </td> 
</tr><tr class="data"><th class="route_number"><a href="/routes/west-midlands/B002/?tab=" title="Birmingham City Centre - Sparkbrook - Yardley Wood - Warstock/Maypole"><span class="route_number small_curvy">2</span></a></th> 
    <td class="main_and_via"> 
    <a href="/routes/west-midlands/B002/?tab=" title="Birmingham City Centre - Sparkbrook - Yardley Wood - Warstock/Maypole">Birmingham City Centre - Sparkbrook - Yardley Wood - Warstock/Maypole</a> 
      <span class="via"><strong>via</strong> Yardley Wood Road</span> 
      </td> 
</tr> 

通過每個tr然後有單獨的查詢循環的route numberanchor textvia text理想或可將其與一個單一的XPath查詢做些什麼呢?

+0

不會真的不僅僅是有什麼不同使用getAttribute()和getElementsByClassName – runspired

回答

0

您可以使用XPath的 「上下文」 支持:

$tr = $xpath->query("//tr[@class='data']"); 

foreach($tr as $row) { 
    $route = $tr->query("//td[contains(@class, 'route_number')]", $row); 
    etc... 
} 

注意$row在第二 - >查詢()調用。它爲搜索的開始位置提供了上下文。 xpath將只搜索$ row指向的特定分支,而不是搜索整個DOM樹。

這樣做可以保證您找到的.route_number屬於您正在處理的$行,而不是樹中其他位置的.router_number。

0

可以查詢,你希望他們所有這些值,如果他們總是存在:

(
    (//tr[@class = "data"]) 
     /*[@class="route_number"]//span 
     |//tr[@class = "data"]/*[@class="main_and_via"]/a 
     |//tr[@class = "data"]//*[@class="via"] 
)/text() 

結果:

#0: DOMText (length: 1) "1" 
#1: DOMText (length: 50) "Dudley - Sedgley - Wolverhampton - Tettenhall Wood" 
#2: DOMText (length: 32) " Dudley Road and Tettenhall Road" 
#3: DOMText (length: 1) "2" 
#4: DOMText (length: 71) "Birmingham City Centre - Sparkbrook - Yardley Wood - Warstock/Maypole" 
#5: DOMText (length: 18) " Yardley Wood Road" 

See it in action.