2

我试图弄清楚如何解析网站以从表格中获取链接。在我的特殊情况下,有两个表,但我只想要第二个表(Link5 和 Link6)中的链接。这是我要解析的 HTML。

<html>
<head>
</head>
<body>
<a href="http://www.example.com/link1.html">Link1</a><br>
<br>
<table>
  <tbody>
    <tr>
      <td><a href="http://www.example.com/link2.html">Link2</a></td>
      <td>dog</td>
      <td>fish</td>
    </tr>
    <tr>
      <td><a href="http://www.example.com/link3.html">Link3</a></td>
      <td>cat</td>
      <td>bird</td>
    </tr>
  </tbody>
</table>
<br>
<a href="http://www.example.com/link4.html">Link4</a><br>
<br>
<table>
  <tbody>
    <tr>
      <td><a href="http://www.example.com/link5.html">Link5</a></td>
      <td>cow</td>
    </tr>
    <tr>
      <td><a href="http://www.example.com/link6.html">Link6</a></td>
      <td>horse</td>
    </tr>
  </tbody>
</table>
<br>
<a href="http://www.example.com/link7.html">Link7</a><br>
</body>
</html>

我已经读到 DOM 是一种从网络解析数据的好方法,所以这是我一直在处理的代码。

<?php
$link = array();

//new dom object
$dom = new DOMDocument();

//load the html
$html = $dom->loadHTMLFile('http://www.example.com');

//discard white space 
$dom->preserveWhiteSpace = false; 

//get the table by its tag name
$tables = $dom->getElementsByTagName('table');   

$rows = $tables->item(1)->getElementsByTagName('tr');

$i = 0;

//loop over the table rows
foreach ($rows as $row) 
{ 
    $links = $row->getElementsByTagName('a');


    //put node value into an array
    $link[] = $links->item(0)->nodeValue;

    // echo the values
    echo $link[$i] . '<br />';

    $i++;
} 

?>

此代码给出以下输出: Link5 Link6

但我想要实现的是: http ://www.example.com/link5.html http://www.example.com/link6.html

任何帮助将不胜感激。

4

2 回答 2

0

我想问题是你想得到href不是节点的值。所以你应该使用getAttribute

于 2012-11-22T10:02:56.960 回答
0
$link[] = $links->item(0)->getAttribute("href");
于 2012-11-22T10:03:59.843 回答