我在哪里可以找到DOM解析器?

时间:2011-12-02 18:54:11

标签: php dom web-scraping

我需要从html页面阅读一些内容。 我已对simple_html_dom进行了测试,但它根本无法满足我的需求。

我需要这样的东西(基于simple_html_dom的pseaudo语法):

$html = file_get_contents($url);
$html_obj = parse_html($html);

$title = $html_obj->get('title');
$meta1 = $html_obj->get('meta[name=description]', 'innertext']; //text only
$meta2 = $html_obj->get('meta[name=keywords]', 'innertext']; // text only
$content = $html_obj->get('div[id=section_a]', outerText); //html code

我已经在很多方面测试了simple_html_dom,并且只设法获得了我需要的部分内容。 它根本不简单"。

我还测试了PHP DOMDocument::loadHTML,但我遇到了处理内联<script>的问题。

是否有任何php库可以像jQuery一样轻松获取内容?

更新

我的一个问题是来自添加代理机构的第三方javascript:

    <script language="javascript" type="text/javascript">
      <!--
        if (window.adgroupid == undefined) {
          window.adgroupid = Math.round(Math.random()*100000);
        }
        document.write('<scr'+'ipt language="javascript1.1" type="text/javascript" src="http://adserver.adtech.de/addyn|3.0|994|3159100|0|-1|size=980x150|ADTECH;loc=100;target=_blank;key=startside,kvinner, kvinnesak, bryllup, graviditet, mamma, kosmetikk, markedsplass, dagbok, feminisme;grp='+window.adgroupid+';misc='+new Date().getTime()+'"></scri'+'pt>');
      //-->
      </script>

即使我将<scr'+'ipt更改为<script,它也会向我提供无效的JavaScript代码。

2 个答案:

答案 0 :(得分:2)

您可以将DOMDocument与DOMXPath一起使用..

<?php
$DOMDocument = new DOMDocument();
//libxml_use_internal_errors ( true ) ;
$DOMDocument->loadHTMLFile ( 'http://www.iconfinder.com' ) ;
$XPath = new DOMXPath( $DOMDocument );

$title = $DOMDocument->getElementsByTagName('title')->item(0)->nodeValue;
echo $title ;

#$desc = $XPath->query('//meta[@name=description]')->item(0)->getAttribute ( 'content' );
#$keywords = $XPath->query('//meta[@name=keywords]')->item(0)->getAttribute( 'content' );
#$content = $XPath->query('//div[@id=section_a]')->item(0)->nodeValue;

答案 1 :(得分:1)

PHPQuery(http://code.google.com/p/phpquery/)允许您通过类似语法的jquery来操作HTML

相关问题