从 Simple Html Dom 中排除不需要的 html - PHP

Exclude non wanted html from Simple Html Dom - PHP

提问人:Faisal Shani 提问时间:4/3/2020 更新时间:4/4/2020 访问量:285

问:

我正在使用带有 PHP 的 HTML Simple Dom Parser 从网站获取标题、描述和图像。我面临的问题是我得到了我不想要的html以及如何排除这些html标签。以下是解释。

下面是一个正在解析的 html 结构示例。

<div id="product_description">
<p> Some text</p>
<ul>
<li>value 1</li>
<li>value 2</li>
<li>value 3</li>
</ul>

// the div I dont want
<div id="comments">
<h1> Some Text </h1>
</div>

</div>

我正在使用下面的php脚本进行解析,

foreach($html->find('div#product_description') as $description)
{
    echo $description->outertext ;
    echo "<br>";
}

上面的代码解析了 id 为“product_description”的 div 中的所有内容。我想排除 Id 为“comments”的 div。我试图将其转换为字符串,然后使用 substr 排除最后一个字符,但这不起作用。不知道为什么。关于我该怎么做的任何想法?任何允许我从解析的 html 中排除 div 的方法都将起作用。谢谢

php 网页抓取 解析 simple-html-dom

评论


答:

1赞 Nima 4/3/2020 #1

您可以通过设置以下元素来删除不需要的元素:outertext = ''

$src =<<<src
<div id="product_description">
    <p> Some text</p>
    <ul>
        <li>value 1</li>
        <li>value 2</li>
        <li>value 3</li>
    </ul>

    <!-- the div I don't want -->                                                                                                                                        
    <div id="comments">
        <h1> Some Text </h1>
    </div>

</div>
src;

$html = str_get_html($src);

foreach($html->find('#product_description') as $description)
{
    $comments = $description->find('#comments', 0); 
    $comments->outertext = ''; 
    print $description->outertext ;
}

评论

0赞 Faisal Shani 4/3/2020
感谢您的回复。我不明白你为什么要使用$src变量?这会容纳这个对象吗 $html->find('div#product_description') ?
0赞 Nima 4/3/2020
不,它只是一个保存 HTML 的变量,所以我可以将其传递给函数,只是为了使代码完全运行以进行演示。str_get_html
0赞 Faisal Shani 4/3/2020
非常感谢。我没有使用 $html = str_get_html($src);和 $src 变量。这是我使用的代码。foreach($html->find('div#ProductDescription_Tab') as $description) { $comments = $description->find('.hsn_comments', 0); $comments->outertext = ''; print $description->outertext ; }
0赞 Faisal Shani 4/4/2020 #2

好的,所以我自己弄清楚了,只需使用高级 Html Dom 库,它与简单的 html dom 完全兼容,通过使用它,您将获得更多的控制权。从解析的 html 中删除您想要的内容非常简单。例如。

//to remove script tag
$scripts = $description->find('script')->remove;

//to remove css style tag
$style = $description->find('style')->remove;

// to remove a div with class name findify-element
$findify = $description->find('div.findify-element')->remove;

在此处输入链接描述