【问题标题】:Need a good HTML parser on php需要一个好的 php 上的 HTML 解析器
【发布时间】:2010-12-24 19:32:10
【问题描述】:

找到了这个http://simplehtmldom.sourceforge.net/,但是没有成功

extracting this page http://php.net/manual/en/function.curl-setopt.php
and parse it to plain html, it failed and returned a partial html page

这就是我想做的, 转到一个 html 页面并获取单个组件(层次结构中所有 div 和 p 的内容) 我喜欢 simplehtmldom 的特性,需要任何擅长所有代码(最好和最差)的解析器。

【问题讨论】:

    标签: html parsing


    【解决方案1】:

    我经常使用DOMDocument::loadHTML,在一般情况下效果还不错——而且我喜欢在将文档加载为 DOM 后使用Xpath 查询文档。

    不幸的是,我想,在某些情况下,如果 HTML 页面的格式真的很糟糕,可能会出现一些解析问题...... 这时你开始明白尊重网络标准是个好主意。 ..

    【讨论】:

    • 好吧,作为一个必须解析其他人的代码的人,尊重非网络标准是完全不相关的:-)
    • @Johannes > 确实 ;;但是,如果您尝试解析别人的 HTML,那么总有一天您可能也必须生成 HTML……而且,那天,记住您在解析糟糕的 HTML 时遇到的困难可能会鼓励您编写干净的 HTML (希望...)
    【解决方案2】:

    基于 Pascal MARTIN 的回应...

    我使用 CURL 和 XPATH 的组合。下面是我在我的一个类中使用的一个函数。

    protected function _get_xpath($url) {
        $refferer='http://www.whatever.com/';
        $useragent='Googlebot/2.1 (http://www.googlebot.com/bot.html)';
        // create curl resource
        $ch = curl_init();
    
        // set url
        curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
        curl_setopt ($ch, CURLOPT_REFERER, $refferer);
        curl_setopt($ch, CURLOPT_URL, $url);
    
        //return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
        // $output contains the output string
        $output = curl_exec($ch);
        //echo htmlentities($output);
    
        if(curl_errno($ch)) {
            echo 'Curl error: ' . curl_error($ch);
        }
        else {
            $dom = new DOMDocument();
            @$dom->loadHTML($output);
            $this->xpath = new DOMXPath($dom);
            $this->html = $output;
        }
    
        // close curl resource to free up system resources
        curl_close($ch);
    }
    

    然后您可以使用evaluate 解析文档结构并提取您想要的信息

    $resultDom = $this->xpath->evaluate("//span[@id='headerResults']/strong");
    $this->results = $resultDom->item(0)->nodeValue;
    

    【讨论】:

      【解决方案3】:

      我在这里找到了最适合我的一个 - http://querypath.org/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-17
        • 1970-01-01
        • 2017-03-06
        • 2020-09-04
        • 1970-01-01
        相关资源
        最近更新 更多