繁体   English   中英

如何在没有javascript代码的情况下获取正文内容

[英]How to get body content without javascript code

要获取body标签中的内容,我使用下面的代码。

$html = @file_get_contents($url);
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('body');
$body = $nodes->item(0)->nodeValue;

如何从$ body中删除js代码? 任何看起来像js的代码

<script> /*Some js code*/ </script>

尝试这个:

$html = preg_replace("/<script.*?\/script>/s", "", $html);

在做正则表达式时,事情可能会出错,所以这样做更安全:

$html = preg_replace("/<script.*?\/script>/s", "", $html) ? : $html;

因此,当“意外”发生时,我们得到原始的$html而不是空字符串。

如果您已经在使用DOMDocument那么为什么不删除那些节点?!

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
@$dom->loadHTMLFile("from_link_to.html");
$scripts = $dom->getElementsByTagName('script');
foreach ($scripts as $script) {
    $scripts->removeChild($script);
}
...

仔细看看DOMDocument类,以及regular expression对于此类任务的噩梦

这里的解决方案解决我的问题。 下面的代码完全从body标签中删除脚本标记及其内容:

$doc = new DOMDocument();
    $doc->preserveWhiteSpace = false;
    @$doc->loadHTML($html);
    $script = $doc->getElementsByTagName('script');

    $remove = [];
    foreach ($script as $item) {
        $remove[] = $item;
    }

    foreach ($remove as $item) {
        $item->parentNode->removeChild($item);
    }

    $node = $doc->getElementsByTagName('body');
    $body = $node->item(0)->nodeValue;

    echo $body;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM