下面我们就给人人引见如何用PHP做一个简朴的网页爬虫!
实在从另一个网站猎取一个标签并剖析数据是异常轻易的。能够经由过程一个PHP函数file_get_contents
来完成,以下所示:
<?php $webpage = file_get_contents('http://www.tonylea.com'); ?>
如今,变量$webpage
包括了http://www.tonylea.com的一切标签(源)。
基本上,假如我们想要剖析数据,我们就能够如许做:
<?php $url = 'http://www.tonylea.com'; $webpage = file_get_contents($url); function get_images($page) { if (!empty($page)){ preg_match_all('/<img([^>]+)\/>/i', $page, $images); return !empty($images[1]) ? $images[1] : FALSE; } } function get_links($page) { if (!empty($this->markup)){ preg_match_all('/<a([^>]+)\>(.*?)\<\/a\>/i', $this->markup, $links); return !empty($links[1]) ? $links[1] : FALSE; } } $images = get_images($webpage); foreach($images as $image) { echo $image.'<br />'; } ?>
在上面的示例中,我们从指定的URL取得了标记,并取得了'a'标签和'img'标签中包括的值。然后代码打印出“img”标签中的数据。经由过程更多的剖析,你能够显现从已抓取或匍匐的页面中取得的图象和链接。
以上就是PHP能写爬虫吗?(PHP完成爬虫手艺示例)的细致内容,更多请关注ki4网别的相干文章!