PHP数据神偷第二步simple_html_dom使用心得
自己造轮子实在是太累了,而且质量不忍直视,所以呢,我决定造自行车啦。
官方在线文档 http://simplehtmldom.sourceforge.net/
<?php /** * Created by PhpStorm. * User: Code * Date: 2016/7/1 * Time: 8:34 */ header("Content-type:text/html;charset=utf-8");//设置php编码格式,防止出现乱码的情况 include "simple_html_dom.php"; //引入simple_html_dom.php 框架文件(轮子文件) //$html=file_get_html('http://www.baidu.com'); //设置要抓取数据的网址 //foreach ($html->find('img') as $element) //从抓取数据中查找img节点,遍历 // echo $element; //输出遍历的img数据,显示为一张图片 //foreach ($html->find('a') as $element) //从抓取数据中查找a节点,遍历输出 // echo $element->href.'<br>';//输入a节点中href属性的value $html=str_get_html('<div id="s_form_wrapper">1111<div>');//向界面中添加div和显示的内容 $html->find('div',0)->class="lijian"; //设置div的class属性 $html->find('div[id=hello]', 0)->innertext = 'foo';//设置id为hello的内容 echo $html; //输出页面 //echo file_get_html('http://www.baidu.com/')->plaintext; //输出抓取页面中的文字
-------------------------------------------------------------------------------------- 输出页面中指定部分的信息 $html=file_get_html('http://www.lezhi.ren'); foreach($html->find('article[id=post-511]') as $articles) { $item['title']=$articles->find('div.info-bar',0)->plaintext; // $item['intro'] = $article->find('div.intro', 0)->plaintext; // $item['details'] = $article->find('div.details', 0)->plaintext; echo $item['title']; }//输出指定信息,那么小爬虫程序,分析数据,是不是就可以实现了呢,哈哈哈哈。
知识点:
find详解
find ( string $selector [, int $index] )
// Find allanchors, returns a array of element objects,注意,返回数组 $ret = $html->find('a'); // Find (N)th anchor, returns element object or null if not found (zero based) $ret = $html->find('a', 0); // Find lastest anchor, returns element object or null if not found (zero based) $ret = $html->find('a', -1); // Find all <div> with the id attribute $ret = $html->find('div[id]'); // Find all <div> which attribute id=foo $ret = $html->find('div[id=foo]'); // Find all element which id=foo $ret = $html->find('#foo'); // Find all element which class=foo $ret = $html->find('.foo'); // Find all element has attribute id $ret = $html->find('*[id]'); // Find all anchors and images $ret = $html->find('a, img'); // Find all anchors and images with the "title" attribute $ret = $html->find('a[title], img[title]'); // Find all <li> in <ul> $es = $html->find('ul li'); // Find Nested <div> tags 嵌套div $es = $html->find('div div div'); // Find all <td> in <table> which class=hello $es = $html->find('table.hello td'); // Find all td tags with attribite align=center in table tags $es = $html->find(''table td[align=center]');
Element的用法
DOM方法使用
参考新浪博客:http://blog.sina.com.cn/s/blog_691051e101014dlg.html