How do I fetch just the beginning of a Web page with LWP?

回眸只為那壹抹淺笑 提交于 2019-12-01 09:16:55

问题


Does anyone know the best way to fetch just 50% of the Web page on a GET or POST request? The Web page I fetch takes me 10, 20 seconds to completely load, and I only need to filter just a few lines from the beginning of the page.


回答1:


use 5.010;
use strictures;
use LWP::UserAgent qw();

my $content;
LWP::UserAgent->new->get(
    $url,
    ':content_cb' => sub {
        my ($chunk, $res) = @_;
        state $length = $res->header('Content-Length');
        $content .= $chunk;
        die if length($content) / $length > 0.5;
    },
);



回答2:


If the web site in question suppplies the Content-Length header you can just ask how much data is going to be sent and request only half of it.

This code demonstrates.

use strict;
use warnings;

use LWP;

my $ua = LWP::UserAgent->new;
my $url = 'http://website.test';

my $resp = $ua->head($url);
my $half = $resp->header('Content-Length') / 2;

$resp = $ua->get($url, Range => "bytes=1-$half");
my $content = $resp->content;



回答3:


If the web application needs a long time to render the page you will usually have no possibility to accellerate the process by fetching 'half' of the page.

The page will be delivered after all the database queries and the actual rendering is done. And those are likely the reason for the long delays.



来源:https://stackoverflow.com/questions/10984127/how-do-i-fetch-just-the-beginning-of-a-web-page-with-lwp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!