PHP简单爬虫&HTML DOM解析器&抓取网站内容

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuxiongyin/article/details/83930493

PHP简单爬虫&HTML DOM解析器&抓取网站内容

简介

为了能简单地用PHP爬取网站上的内容,用了HTMLDOM解析器简单地抓取内容。练习下如何地神奇。
simple_html_dom的下载文档地址:在线文档
为了方便这是解析器文件:文件下载

实例

网站的抓取比较广,就不多分析了,只是简单地网页抓取测试。

例如你的网页index.html

<ul class="list">
	<li>
		<a heft="index.html">抓取的数据内容</a>
	</li>
</ul>

php代码

<?php
header("Content-type:text/html;charset=utf-8");

//引用解析器文件
include_once 'simple_html_dom.php';
//使用file_get_html获取html数据转化为对象
//你要转化的网站地址index.html
$html = file_get_html('index.html');

//在类标签内class='list',使用find方法查找数据内容 
foreach($html->find('.txt-list li a') as $element)
//多条数据行可以用<br />等划分,例如:innertext . <br>。
$arr[]= $element->innertext;

//自动生成文件
$fileName='data.txt';
$arrLen=count($arr);
for($i=0;$i<$arrLen;$i++){
	
	//FILE_APPEND|LOCK_EX 是往后追加数据
	file_put_contents($fileName,$arr[$i],FILE_APPEND|LOCK_EX);
}
//抓取的数据保存到data.txt
$content=file_get_contents($fileName);
$cont=explode("<br>",$content);
$contLen=count($cont);
for($i=0;$i<$contLen;$i++) {
	unset($cont[2*$i+1]);
}

猜你喜欢

转载自blog.csdn.net/zhuxiongyin/article/details/83930493