利用curl获取页面所有链接

一般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://www.hao123.com/'); // 只需返回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 = 'http://www.hao123.com/'; if (is_array($linkarr)) { foreach ($linkarr as $k => $v) { $linkresult[$k] = _expandlinks($v, $host); } } printf("<p>此页面的所有链接为:</p><pre>%s</pre>\n", var_export($linkresult , true)); ?>

function.php中为以下内容

<?php function _striplinks($document) { preg_match_all("'<\s*a\s.*?href\s*=\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( "|^".preg_quote($host)."|i", "|^(\/)|i", "|^(?!)(?!mailto:)|i", "|/\./|", "|/[^\/]+/\.\./|" ); $replace = array( "", $match_root."/", $match."/", "/", "/" ); $expandedLinks = preg_replace($search,$replace,$links); return $expandedLinks; } ?>

匹配链接函数先容: function _striplinks()

相对路径转绝对先容:function _expandlinks()

获得的功效很满足。都获取到了链接,而且比file_get_contents快了3、4秒这样。

CURL自己就是操作URL语法在呼吁行方法下事情的文件传输东西。很容易就获取到网页数据,并且速度很快。那来收罗是最好不外了,今后我将用CURL取代file_get_contents、file了。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/7870.html