仅对页面标题进行爬网

时间:2012-05-05 19:18:17

标签: php web-crawler

我一直在寻找互联网,希望这是可能的,我基本上只需要获得一个网页的标题而不是别的。

网页抓取工具可能需要很长时间才能执行任务,因为他们必须在检查之前加载网页,这对我想要实现的目标来说效率低下......这就是我到目前为止所拥有的

php代码

$url = 'http://www.ebay.com/itm/300702997750#ht_500wt_1156';
$str = file_get_contents($url);
$title = ''; 

if(strlen($str)>0){
   preg_match("/\<title\>(.*)\<\/title\>/",$str,$titleArr);
   $title = $titleArr[1];
}

我想知道是否可以只抓取部分页面(例如页面的前2000个字符)。

任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:4)

你可以使用substr来获取前1000个字符,或者你可以使用

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch, CURLOPT_RANGE, '0-500');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
echo $result;

只会下载前500个字节。你可以通过运行这样非常丑陋的垃圾代码来解决这个问题:

$url = 'http://www.example.com/';
$range = array();
$repeats = 10;

function average($a){
  return array_sum($a)/count($a) ;
}

for ($i=0;$i<$repeats;$i++) {
    $time_start = microtime(true);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RANGE, '0-500');
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);

    $time_end = microtime(true);
    $time = $time_end - $time_start;
    curl_close($ch);
    $range[] = $time;
}
echo "With range: average = ".round(average($range),2)." seconds (Min: ".round(min($range),2).", Max: ".round(max($range),2).")\n";

$range = array();

for ($i=0;$i<$repeats;$i++) {
    $time_start = microtime(true);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);

    $time_end = microtime(true);
    $time = $time_end - $time_start;
    curl_close($ch);
    $range[] = $time;
}
echo "Without range: average = ".round(average($range),2)." seconds (Min: ".round(min($range),2).", Max: ".round(max($range),2).")\n";

如果我在我的网站上运行(http://www.focalstrategy.com/),我会得到:

With range: average = 0.38 seconds (Min: 0.35, Max: 0.41)
Without range: average = 0.56 seconds (Min: 0.53, Max: 0.7)

反对http://en.wikipedia.org/wiki/PHP,我得到:

With range: average = 0.11 seconds (Min: 0.05, Max: 0.5)
Without range: average = 0.48 seconds (Min: 0.34, Max: 0.78)

反对Stack Overflow我得到:

With range: average = 1.31 seconds (Min: 1.1, Max: 1.46)
Without range: average = 1.37 seconds (Min: 1.18, Max: 1.7)

反对eBay我得到:

With range: average = 1.75 seconds (Min: 1.56, Max: 1.99)
Without range: average = 1.74 seconds (Min: 1.51, Max: 2.14)

您可以通过测试看到SO和eBay不支持范围请求。

总而言之,支持此功能的网站会加快速度,而那些不支持的网站则会加速,您只会获得整个代码。