网站建设资讯

NEWS

网站建设资讯

php爬取页面数据 php实现爬虫

php的curl怎么爬取网页内容

创建一个新cURL资源

在网站设计制作、成都网站建设中从网站色彩、结构布局、栏目设置、关键词群组等细微处着手,突出企业的产品/服务/品牌,帮助企业锁定精准用户,提高在线咨询和转化,使成都网站营销成为有效果、有回报的无锡营销推广。创新互联专业成都网站建设十余年了,客户满意度97.8%,欢迎成都创新互联客户联系。

设置URL和相应的选项

抓取URL并把它传递给浏览器

关闭cURL资源,并且释放系统资源

代码案例:

php如何爬取微博热门视屏

1.访问 genvisitor 获取一个tid.

2.用tid 先获取一个 cookie,同时得到2个参数 sub subp。

3.带着获得的cookie,和sub subp 2个参数 获得第二个cookie。

4.最后用第二个cookie访问要抓取的页面。

php中curl爬虫 怎么样通过网页获取所有链接

本文承接上面两篇,本篇中的示例要调用到前两篇中的函数,做一个简单的URL采集。一般php采集网络数据会用file_get_contents、file和cURL。不过据说cURL会比file_get_contents、file更快更专业,更适合采集。今天就试试用cURL来获取网页上的所有链接。示例如下:

?php

/*

* 使用curl 采集hao123.com下的所有链接。

*/

include_once('function.php');

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, '');

// 只需返回HTTP header

curl_setopt($ch, CURLOPT_HEADER, 1);

// 页面内容我们并不需要

// curl_setopt($ch, CURLOPT_NOBODY, 1);

// 返回结果,而不是输出它

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$html = curl_exec($ch);

$info = curl_getinfo($ch);

if ($html === false) {

echo "cURL Error: " . curl_error($ch);

}

curl_close($ch);

$linkarr = _striplinks($html);

// 主机部分,补全用

$host = '';

if (is_array($linkarr)) {

foreach ($linkarr as $k = $v) {

$linkresult[$k] = _expandlinks($v, $host);

}

}

printf("p此页面的所有链接为:/ppre%s/pren", var_export($linkresult , true));

?

function.php内容如下(即为上两篇中两个函数的合集):

?php

function _striplinks($document) {

preg_match_all("'s*as.*?hrefs*=s*(["'])?(?(1) (.*?)\1 | ([^s]+))'isx", $document, $links);

// catenate the non-empty matches from the conditional subpattern

while (list($key, $val) = each($links[2])) {

if (!empty($val))

$match[] = $val;

} while (list($key, $val) = each($links[3])) {

if (!empty($val))

$match[] = $val;

}

// return the links

return $match;

}

/*===================================================================*

Function: _expandlinks

Purpose: expand each link into a fully qualified URL

Input: $links the links to qualify

$URI the full URI to get the base from

Output: $expandedLinks the expanded links

*===================================================================*/

function _expandlinks($links,$URI)

{

$URI_PARTS = parse_url($URI);

$host = $URI_PARTS["host"];

preg_match("/^[^?]+/",$URI,$match);

$match = preg_replace("|/[^/.]+.[^/.]+$|","",$match[0]);

$match = preg_replace("|/$|","",$match);

$match_part = parse_url($match);

$match_root =

$match_part["scheme"]."://".$match_part["host"];

$search = array( "|^http://".preg_quote($host)."|i",

"|^(/)|i",

"|^(?!http://)(?!mailto:)|i",

"|/./|",

"|/[^/]+/../|"

);

$replace = array( "",

$match_root."/",

$match."/",

"/",

"/"

);

$expandedLinks = preg_replace($search,$replace,$links);

return $expandedLinks;

}

?


本文题目:php爬取页面数据 php实现爬虫
当前链接:http://cdweb.net/article/doeejce.html