PHP在<pre> tags</pre>之间抓取HTML

时间:2011-11-09 03:20:13

标签: php screen-scraping scrape pre

我无法找到如何使用PHP5从

 and 
标签内部抓取HTML内容。

我想以下面的文档为例,取2个(或更多预标记区域,动态)并将其推送到数组中。

blablabla
<pre>save
this
really</pre>
not this
<pre>save this too
really
</pre>
but not this

如何将另一台服务器上的html文件的预标签之间的区域推送到数组中。

3 个答案:

答案 0 :(得分:1)

我建议使用xpath

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DomXpath($doc);

$pre_tags = array();
foreach($xpath->query('//pre') as $node){
    $pre_tags[] = $node->nodeValue;
}

答案 1 :(得分:0)

假设HTML格式正确,您可以执行以下操作:

$pos = 0;
$insideTheDiv = array();
while (($pos = strpos($theHtml, "<pre>", $pos)) !== false) {
    $pos += 5;
    $endPrePos = strpos($theHtml, "</pre>", $pos);
    if ($endPrePos !== false) {
        $insideTheDiv[] = substr($theHtml, $pos, $endPrePos - $pos);
    } else break;
}

完成后,$insideTheDiv应该是pre代码的所有内容的数组。

演示:http://codepad.viper-7.com/X15l7P(它从输出中删除换行符)

答案 2 :(得分:0)

您可以简单地使用正则表达式来提取预标签中的所有内容。

在python中:

re.compile('<pre>(.*?)</pre>', re.DOTALL).findall(html)