本文共 848 字,大约阅读时间需要 2 分钟。
php能做爬虫吗?php能写爬虫吗?提到网页爬虫,大家肯定第一时间想到是Python做爬虫。其实用PHP也可以实现网页爬虫功能!
下面我们就给大家介绍如何用PHP做一个简单的网页爬虫!
其实从另一个网站获取一个标签并解析数据是非常容易的。可以通过一个PHP函数file_get_contents来完成,如下所示:
$webpage = file_get_contents('http://www.tonylea.com');
?>
现在,变量$webpage包含了http://www.tonylea.com的所有标签(源)。
基本上,如果我们想要解析数据,我们就可以这样做:
$url = 'http://www.tonylea.com';
$webpage = file_get_contents($url);
function get_images($page)
{
if (!empty($page)){
preg_match_all('/]+)\/>/i', $page, $images);
return !empty($images[1]) ? $images[1] : FALSE;
}
}
function get_links($page)
{
if (!empty($this->markup)){
preg_match_all('/]+)\>(.*?)\/i', $this->markup, $links);
return !empty($links[1]) ? $links[1] : FALSE;
}
}
$images = get_images($webpage);
foreach($images as $image)
{
echo $image.'
';}
?>
在上面的示例中,我们从指定的URL获得了标记,并获得了'a'标签和'img'标签中包含的值。然后代码打印出“img”标签中的数据。通过更多的解析,你可以显示从已抓取或爬行的页面中获得的图像和链接。
转载地址:http://zeexl.baihongyu.com/