PHP 网页爬虫:Simple HTML DOM解析器使用入门 (web crawler)

 

下载地址:https://github.com/samacs/simple_html_dom

文档地址 http://simplehtmldom.sourceforge.net/

中文手册:http://microphp.us/plugins/public/microphp_res/simple_html_dom/manual.htm

下载:simplehtmldom_1_5

一直以来使用php解析html文档树都是一个难题。Simple HTML DOM parser 帮我们很好地解决了使用 php html 解析 问题。可以通过这个php类来解析html文档,对其中的html元素进行操作 (PHP5+以上版本)。

解析器不仅仅只是帮助我们验证html文档;更能解析不符合W3C标准的html文档。它使用了类似jQuery的元素选择器,通过元素的id,class,tag等等来查找定位;同时还提供添加、删除、修改文档树的功能。当然,这样一款强大的html Dom解析器也不是尽善尽美;在使用的过程中需要十分小心内存消耗的情况。不过,不要担心;本文中,笔者在最后会为各位介绍如何避免消耗过多的内存。

 

如何使用php html 解析

上传类文件以后,有三种方式调用这个类:

从url中加载html文档

从字符串中加载html文档

从文件中加载html文档

<?php
// 新建一个Dom实例
$html = new simple_html_dom();
 
// 从url中加载
$html->load_file('http://www.cnphp.info/php-simple-html-dom-parser-intro.html');
 
// 从字符串中加载
$html->load('<html><body>从字符串中加载html文档演示</body></html>');
 
//从文件中加载
$html->load_file('path/file/test.html');
?>

 

如果从字符串加载html文档,需要先从网络上下载。建议使用cURL来抓取html文档并加载DOM中。

DOM的方法

$html = file_get_html('http://www.google.com/');        //$html 所拥有的方法如下表所示
$html->clear() ;                                        //调用方法

 

DOM methods & properties

Name Description
void

__construct ( [string $filename] )

Constructor, set the filename parameter will automatically load the contents, either text or file/url.
 string

plaintext

Returns the contents extracted from HTML.
void

clear ()

Clean up memory.
void

load ( string $content )

Load contents from a string.
string

save ( [string $filename] )

Dumps the internal DOM tree back into a string. If the $filename is set, result string will save to file.
void

load_file ( string $filename )

Load contents from a from a file or a URL.
void

set_callback ( string $function_name )

Set a callback function.
mixed

find ( string $selector [, int $index] )

Find elements by the CSS selector. Returns the Nth element object if index is set, otherwise return an array of object.

 

查找html元素

可以使用find函数来查找html文档中的元素。返回的结果是一个包含了对象的数组。我们使用HTML DOM解析类中的函数来访问这些对象,下面给出几个示例:

<?php
 
//查找html文档中的超链接元素
$a = $html->find('a');
 
//查找文档中第(N)个超链接,如果没有找到则返回空数组.
$a = $html->find('a', 0);

// Find lastest anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', -1); 
 
// 查找id为main的div元素
$main = $html->find('div[id=main]',0);
 
// 查找所有包含有id属性的div元素
$divs = $html->find('div[id]');
 
// 查找所有包含有id属性的元素
$divs = $html->find('[id]');

// Find all td tags with attribite align=center in table tags 
$es = $html->find(''table td[align=center]');

// Find all element has attribute id
$ret = $html->find('*[id]'); 
//($product=$table->find("#product *[selected]",0)->innertext ; )不能写成#product[selected].

// Find all anchors and images 
$ret = $html->find('a, img'); 
?>

 

还可以使用类似jQuery的选择器来查找定位元素:

<?php
// 查找id='#container'的元素
$ret = $html->find('#container');
 
// 找到所有class=foo的元素
$ret = $html->find('.foo');
 
// 查找多个html标签
$ret = $html->find('a, img');
 
// 还可以这样用
$ret = $html->find('a[title], img[title]');
?>

 

解析器支持对子元素的查找

<?php
 
// 查找 ul列表中所有的li项
$ret = $html->find('ul li');
 
//查找 ul 列表指定class=selected的li项
$ret = $html->find('ul li.selected');
 
?>

 

如果你觉得这样用起来麻烦,使用内置函数可以轻松定位元素的父元素、子元素与相邻元素

<?php
// 返回父元素
$e->parent;
 
// 返回子元素数组
$e->children;
 
// 通过索引号返回指定子元素
$e->children(0);
 
// 返回第一个资源速
$e->first_child ();
 
// 返回最后一个子元素
$e->last _child ();
 
// 返回上一个相邻元素
$e->prev_sibling ();
 
//返回下一个相邻元素
$e->next_sibling ();
?>
Method Description
mixed

$e->children ( [int $index] )

Returns the Nth child object if index is set, otherwise return an array of children.
element

$e->parent ()

Returns the parent of element.
element

$e->first_child ()

Returns the first child of element, or null if not found.
element

$e->last_child ()

Returns the last child of element, or null if not found.
element

$e->next_sibling ()

Returns the next sibling of element, or null if not found.
element

$e->prev_sibling ()

Returns the previous sibling of element, or null if not found.
// Example
echo $html->find("#div1", 0)->children(1)->children(1)->children(2)->id;
// or 
echo $html->getElementById("div1")->childNodes(1)->childNodes(1)->childNodes(2)->getAttribute('id');

 

元素属性操作

使用简单的正则表达式来操作属性选择器。

[attribute] – 选择包含某属性的html元素

[attribute=value] – 选择所有指定值属性的html元素

[attribute!=value]- 选择所有非指定值属性的html元素

[attribute^=value] -选择所有指定值开头属性的html元素

[attribute$=value] 选择所有指定值结尾属性的html元素

[attribute*=value] -选择所有包含指定值属性的html元素

 

在解析器中调用元素属性

在DOM中元素属性也是对象:

<?php
// 本例中将$a的锚链接值赋给$link变量
$link = $a->href;
?>

或者:

<?php
$link = $html->find('a',0)->href;
?>

每个对象都有4个基本对象属性:

tag – 返回html标签名

innertext – 返回innerHTML

outertext – 返回outerHTML

plaintext – 返回html标签中的文本

$e = $html->find("div", 0);  //$e 所拥有的方法如下表所示
Attribute Name Usage
$e->tag Read or write the tag name of element.
$e->outertext Read or write the outer HTML text of element.
$e->innertext Read or write the inner HTML text of element.
$e->plaintext Read or write the plain text of element.
// Example
$html = str_get_html("<div>foo <b>bar</b></div>"); 
$e = $html->find("div", 0);

echo $e->tag; // Returns: " div"
echo $e->outertext; // Returns: " <div>foo <b>bar</b></div>"
echo $e->innertext; // Returns: " foo <b>bar</b>"
echo $e->plaintext; // Returns: " foo bar"
(注意,与dom中不同,innertext包含html标签)

 

在解析器中编辑元素

编辑元素属性的用法和调用它们是类似的:

<?php
//给$a的锚链接赋新值
$a->href = 'http://justcode.ikeepstudying.com';
 
// 删除锚链接
$a->href = null;
 
// 检测是否存在锚链接
if(isset($a->href)) {
//代码
}
?>

 

解析器中没有专门的方法来添加、删除元素,不过可以变通一下使用:

<?php
 
// 封装元素
$e->outertext = '<div class="wrap">' . $e->outertext . '<div>';
 
// 删除元素
$e->outertext = '';
 
// 添加元素
$e->outertext = $e->outertext . '<div>foo<div>';
 
// 插入元素
$e->outertext = '<div>foo<div>' . $e->outertext;
?>

 

保存修改后的html DOM文档也非常简单:

<?php
$doc = $html;
 
// 输出
echo $doc;
?>

 

如何自定义解析行为? 回调函数

// Write a function with parameter "$element"
function my_callback($element) {
        // Hide all <b> tags 
        if ($element->tag=='b')
                $element->outertext = '';
} 

// Register the callback function with it's function name
$html->set_callback('my_callback');

// Callback function will be invoked while dumping
echo $html;

 

如何避免解析器消耗过多内存

在本文的开篇中,笔者就提到了Simple HTML DOM解析器消耗内存过多的问题。如果php脚本占用内存太多,会导致网站停止响应等一系列严重的问题。解决的方法也很简单,在解析器加载html文档并使用完成后,记得清理掉这个对象就可以了。当然,也不要把问题看得太严重了。如果只是加载了2、3个文档,清理或不清理是没有多大区别的。当你加载了5个10个甚至更多的文档的时候,用完一个就清理一下内存绝对是对自己负责啦^_^

<?php
$html->clear();
?>

 

更多:PHP 网页爬虫, php 抓取网页页面, php解析html, php解析html页面元素, DiDOM解析器使用入门 (web crawler)

PHP 网页爬虫:Simple HTML DOM解析器使用入门 (web crawler)
PHP 网页爬虫:Simple HTML DOM解析器使用入门 (web crawler)

 

本文:PHP 网页爬虫:Simple HTML DOM解析器使用入门 (web crawler)

Loading

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.