php抓取网页phpQuery和simple_html_dom

	include 'simple_html_dom.php';
	//面向过程方式2种读取方式
	$html = file_get_html('http://www.baidu.com');
	$html = str_get_html(file_get_contents('http://www.baidu.com'));

	//面向对象方式2种读取方式
	$html = new simple_html_dom();
	$html->load_file('http://www.baidu.com');
	$html->load(file_get_contents('http://www.baidu.com'));
	foreach($html->find('img') as $img)
	{
		print_r($img->src)."<br>";
	}
    print_r($html->find('img', 0)->src);
    //释放内存
    $html->clear();

    

simple_html_dom的find方法参数一与jquery的模式基本一致,可以使用条件搜索,返回的变量e是一个对象,具有以下几类属性:
$e->tag         与原生js的tagName对应,jquery的$(e).attr('nodeName')对应
$e->outertext   与原生js的outerHTML对应,jquery的$(e).attr('outerHTML')对应
$e->innertext   与原生js的innerHTML对应,jquery的$(e).attr('innerHTML')或$(e).html()对应
$e->plaintext   与原生js的innerText对应,jquery的$(e).attr('innerText')或$(e).text()对应
常用的方法如下:
mixed $e->children(index)   index为索引序号,返回第n个子节点对象
element $e->parent()        返回父节点对象
element $e->first_child()   返回第一个子节点对象
element $e->last_child()    返回最后一个子节点对象
element $e->next_sibling()  返回下一个邻节点对象
element $e->prev_sibling()  返回上一个邻节点对象


    include 'phpQuery-onefile.php';
    phpQuery::newDocumentFile('http://www.safe.gov.cn/AppStructured/hlw/RMBQuery.do');
    $a = pq('#InfoTable tr:eq(1) td');
    foreach ($a as $k=>$v){
        if($k==1){
            echo pq($v)->text();
            echo $v->nodeValue;
        }
    }
    echo pq('#InfoTable')->find('tr:eq(1)')->find('td')->eq(1)->text();
    foreach(pq('img') as $img)
    {
        echo pq($img)->attr('src')."<br>";
    }
    //释放内存
    phpQuery::$documents = array();

可以看出,phpQuery的pq相当于jquery的$符号,使用方式基本一致,查阅jquery手册即可。不过gbk网页需要注意编码问题,因为其解析为utf8编码,网上说可以使用phpQuery::$defaultCharset="GBK"进行申明,但不一定成功,建议在utf8环境下操作,解析获取到想要的内容之后再转码为所需的编码。

https://blog.csdn.net/u012543061/article/details/61194372

猜你喜欢

转载自blog.csdn.net/oHeiZhiShi123/article/details/82706863