最近经常需要采集一些网上的数据,发现一个PHP处理HTML的利器 simple html dom,官方网址是http://simplehtmldom.sourceforge.net/
看了一下文档,使用非常方便,关键是能够用CSS选择器来访问DOM树,和jquery相似,实在是难得的利器
以下是一个测试代码,用于抓取大众点评网上的咖啡分类的所有店铺:
程序:
<?php require_once("simple_html_dom.php"); ini_set('memory_limit','1000M'); ini_set("max_execution_time",6000000); for($i=1;$i<=21;$i++){ $html = file_get_html("http://www.dianping.com/search/category/17/30/g1498p$i/g30g1498"); $as = $html->find('.shopname a'); $sum = 0; foreach($as as $a) { if($a->plaintext != "分店"){ $a->href = "http://www.dianping.com".$a->href; echo $a->outertext."------".$a->href."-------<br>"; $sum++; } } echo "<br><br>第 {$i} 页结束 ,数目:{$sum}<hr>"; } ?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?php
require_once
(
"simple_html_dom.php"
)
;
ini_set
(
'memory_limit'
,
'1000M'
)
;
ini_set
(
"max_execution_time"
,
6000000
)
;
for
(
$i
=
1
;
$i
<=
21
;
$i
++
)
{
$html
=
file_get_html
(
"http://www.dianping.com/search/category/17/30/g1498p$i/g30g1498"
)
;
$as
=
$html
->
find
(
'.shopname a'
)
;
$sum
=
0
;
foreach
(
$as
as
$a
)
{
if
(
$a
->
plaintext
!=
"分店"
)
{
$a
->
href
=
"http://www.dianping.com"
.
$a
->
href
;
echo
$a
->
outertext
.
"------"
.
$a
->
href
.
"-------<br>"
;
$sum
++
;
}
}
echo
"<br><br>第 {$i} 页结束 ,数目:{$sum}<hr>"
;
}
?>
|
数据采集结果,共采集了21页的数据
另外,还有一个更强大的PHP处理HTML的利器,号称和jquery更相似,并且比simplehtmldom强大,但是难学,叫做 phpquery,地址是:http://code.google.com/p/phpquery/