版权声明:俗世凡人行(释) QQ:748507607 https://blog.csdn.net/weixin_41887155/article/details/86106201
目录
一: 基础
1.使用get方法请求一个网页,得到网页内容后可以匹配出对应的内容。
2.使用curl封装一个函数,假设函数名就为get。传入url就能请求指定的网页,将指定网页的HTML代码返回回来。代码如下:
function get($url) {
//初使化curl
$ch = curl_init();
//请求的url,由形参传入
curl_setopt($ch, CURLOPT_URL, $url);
//将得到的数据返回
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//不处理头信息
curl_setopt($ch, CURLOPT_HEADER, 0);
//连接超过10秒超时
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
//执行curl
$output = curl_exec($ch);
//关闭资源
curl_close($ch);
//返回内容
return $output;
}
二: 采集数据
网址为新媒体观察网的新闻列表页:http://www.xmtnews.com/events ,采集下面内容
1.得到采红色区间的html
这个区间从下面的HTML代码开始:
<section class="ov">
在以下代码结束:
<div class="hr-10"></div>
使用preg_match写一个正则表达示就匹配就得到了红色区间的HTML。将匹配到的HTML赋值给变量$area。
匹配的正则表达示如下:
<section class="ov">(.*?)<div class="hr-10"><\/div>/mis'
2.在红色区域匹配标题和标题的URL
我们发现所有的标题都在<h3>标签里面。我们使用preg_match_all写一个正则表达示。
preg_match_all('/<h3><a href="(.*?)" title=".*?"
class="headers" target="_blank">(.*?)<\/a><\/h3>/mis',
$area, $find);
将url和内容匹配出来的内容放置到$find中,将$find数组,打印出来就可以看到匹配的结果了。
如果需要,也可以循环读取显示每一行标题和每一行URL。
三: 代码演示
<?php
$content = get('http://www.xmtnews.com/events');
preg_match('/<section class="ov">(.*?)<div class="hr-10"><\/div>/mis', $content, $match);
//将正则匹配到的内容赋值给$area
$area = $match[1];
preg_match_all('/<h3><a href="(.*?)" title=".*?" class="headers"
target="_blank">(.*?)<\/a><\/h3>/', $area, $find);
var_dump($find);
function get($url) {
//初使化curl
$ch = curl_init();
//请求的url,由形参传入
curl_setopt($ch, CURLOPT_URL, $url);
//将得到的数据返回
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//不处理头信息
curl_setopt($ch, CURLOPT_HEADER, 0);
//连接超过10秒超时
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
//执行curl
$output = curl_exec($ch);
//关闭资源
curl_close($ch);
//返回内容
return $output;
}
?>