【问题标题】:Exclude non wanted html from Simple Html Dom - PHP从 Simple Html Dom 中排除不需要的 html - PHP
【发布时间】:2020-07-15 18:38:17
【问题描述】:

我正在使用带有 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 为“cmets”的 div。我尝试将其转换为字符串,然后使用 substr 排除最后一个字符,但这不起作用。不知道为什么。关于我该怎么做的任何想法?任何允许我从解析的 html 中排除 div 的方法都可以。谢谢

【问题讨论】:

    标签: php parsing web-scraping html-parsing simple-html-dom


    【解决方案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 ;
    }
    

    【讨论】:

    • 感谢您的回复。我不明白你为什么使用 $src 变量?这会保存这个对象 $html->find('div#product_description') 吗?
    • 不,它只是一个保存 HTML 的变量,所以我可以将它传递给 str_get_html 函数,只是为了使代码完全可以用于演示。
    • 非常感谢。我没有使用 $html = str_get_html($src);和 $src 变量。这是我使用的代码。 foreach($html->find('div#ProductDescription_Tab') as $description) { $cmets = $description->find('.hsn_cmets', 0); $cmets->outertext = '';打印 $description->outertext ; }
    【解决方案2】:

    好吧,所以我发现自己只是使用 Advanced 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;
    

    enter link description here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-09
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 2013-09-05
      相关资源
      最近更新 更多