PHP网页抓取

时间:2012-08-06 11:27:36

标签: php regex web-scraping

我使用php web scraping,我希望在星期日得到价格(3.65)下面的html代码:

     <tr class="odd">
       <td >
           <b>Sunday</b> Info
           <div class="test">test</div>
       </td>
       <td>
       &euro; 3.65 *

       </td>
    </tr>

但我没有找到最好的正则表达式来做到这一点...... 我用这个PHP代码:

    <?php
        $data = file_get_contents('http://www.test.com/');

        preg_match('/<tr class="odd"><td ><b>Sunday</b> Info<div class="test">test<\/div><\/td><td>&euro; (.*) *<\/td><\/tr>/i', $data, $matches);
        $result = $matches[1];
    ?>

但没有结果......正则表达式有什么问题? (我认为这是因为新的行/空格?)

5 个答案:

答案 0 :(得分:6)

不要使用正则表达式,HTML不是常规的。

相反,使用像DOMDocument这样的DOM树解析器。这documentation可能会对您有所帮助。

/s开关可以帮助您使用原始正则表达式,但我还没有尝试过。

答案 1 :(得分:3)

问题是标签之间的空格。 有一个换行符,标签和/或空格。

你的正则表达式与他们不匹配。

您还需要为多行设置preg_match!

我认为使用xpath进行抓取更容易。

答案 2 :(得分:2)

尝试用''替换换行符,然后再次执行regexp。

答案 3 :(得分:1)

尝试这种方式:

$uri = ('http://www.test.com/');
$get = file_get_contents($uri);

$pos1 = strpos($get, "<tr class=\"odd\"><td ><b>Sunday</b> Info<div class=\"test\">test</div></td><td>&euro;");
$pos2 = strpos($get, "*</td></tr>", $pos1);
$text = substr($get,$pos1,$pos2-$pos1);
$text1 = strip_tags($text);

答案 4 :(得分:0)

使用PHP DOMDocument对象。我们将从网页中解析HTML DOM数据

    $dom = new DOMDocument();
    $dom->loadHTML($data);

    $trs = $dom->getElementsByTagName('tr'); // this gives us all the tr elements on the webpage

    // loop through all the tr tags
    foreach($trs as $tr) {
        // until we get one with the class 'odd' and has a b tag value of SUNDAY
        if ($tr->getAttribute('class') == 'odd' && $tr->getElementsByTagName('b')->item(0)->nodeValue == 'Sunday') {
            // now set the price to the node value of the second td tag
            $price = trim($tr->getElementsByTagName('td')->item(1)->nodeValue);
            break;
        }

    }

不是使用DOMDocument进行网页抓取,而是有点单调乏味,你可以开始使用SimpleHtmlDomParser,它是开源的。