0

我想从一些 HTML 中提取多个值,我觉得 XPath 可能是执行此操作的理想方式。

我正在考虑做的是遍历每个tr具有该类的类,data然后在循环中获取我需要的数据,即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 number,anchor textvia text理想的单独查询还是可以使用单个 XPath 查询来完成?

4

2 回答 2

0

您可以使用 XPath 的“上下文”支持:

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

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

注意$row第二个 ->query() 调用中的。它提供了搜索应该从哪里开始的上下文。xpath 不会搜索整个 DOM 树,而是仅搜索 $row 指向的特定分支。

这样做可以保证.route_number您找到的是属于您正在处理的 $row 的那个,而不是树中其他地方的 .router_number 。

于 2013-04-12T19:08:09.277 回答
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"

在行动中看到它。

于 2013-04-12T22:17:32.037 回答