php curl 自定义get... 登录

php curl 自定义get方法抓取网页

假设我们使用get方法请求一个网页,得到网页内容后可以匹配出对应的内容。

我们可以使用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;
}

我们现在使用我们所写的get方法,请求网易的一个列表,将标题和url抓取出来。

我们可以先用get方法中传入一个URL。得到这个网址所对应网页的html。

网址为新媒体观察网的新闻列表页:http://www.xmtnews.com/events 。

将红色区域采集下来:

1.png

一、得到采红色区间的html 

这个区间从下面的HTML代码开始:

<section class="ov">

在以下代码结束:

<div class="hr-10"></div>

使用preg_match写一个正则表达示就匹配就得到了红色区间的HTML。将匹配到的HTML赋值给变量$area。

匹配的正则表达示如下:

<section class="ov">(.*?)<div class="hr-10"><\/div>/mis'

二、在红色区域匹配标题和标题的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;
}
?>


下一节
<?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; } ?>
提交 重置代码
章节 评论 笔记 课件
  • 取消 回复 发送
  • 取消 发布笔记 发送