使用perl从html文件中的iframe标记加载数据

时间:2013-10-01 06:15:18

标签: javascript html xml perl iframe

我正在编写一个从html文件中获取数据的perl脚本。我可以使用WWW::Mechanize轻松导航到页面并打印输出文件。但是,我需要获取的数据是iframe标记并具有动态src值。

我还提出了一个使用XML::Parser的想法,因为我有网站XML API。但是,由于我的noobness,我不知道如何获得xml链接。

所以我的问题是:

1st:如何显示或从iframe标签获取数据

第二:如何从网站上获取xml链接。

这是我的代码

#!/usr/bin/perl
use strict;
use warnings;

use Getopt::Std;
use XML::Simple;
use WWW::Mechanize;
use HTTP::Cookies;
use LWP::Debug qw(+);


my $username = $opt_u;
my $password = $opt_p;

my $outfile = "out.html";

my $url = "https://t-square.gatech.edu/portal";
my $mech = WWW::Mechanize->new();
$mech->cookie_jar(HTTP::Cookies->new());
$mech->get($url);

$mech->follow_link(text => "Login", n => 1);
$mech->submit_form(
    form_id=> 'fm1',
    fields => { username    => $username,
                password    => $password
              },
    button => 'submit',
);
$mech->follow_link(text => "CS-2200-A,GR SUM13", n => 1);
my $response = $mech->follow_link(text => "Assignments", n => 1);
$response = $mech->get('https://t-square.gatech.edu/portal/tool/3a34f619-99d1-4548-be57-     9ee977fd8127?panel=Main');
my $content = $response->decoded_content();
my $parser = new XML::Simple;
my $data = $parser->XMLin($content);
print Dumper($data);
my $output_page = $mech->content();
open(OUTFILE, ">$outfile");
print OUTFILE "$output_page";
close(OUTFILE);

这是我的out.htm的一个输出,其中框架是src所在的位置。

...
<iframe name="Main3a34f619x99d1x4548xbe57x9ee977fd8127"
    id="Main3a34f619x99d1x4548xbe57x9ee977fd8127"
    title="Assignments "
    class ="portletMainIframe"
    height="475"
    width="100%"
    frameborder="0"
    marginwidth="0"
    marginheight="0"
    scrolling="auto"
    src="https://t-square.gatech.edu/portal/tool/3a34f619-99d1-4548-be57-9ee977fd8127?panel=Main">**
</iframe>
...

我需要的数据是在frame标签内的src链接中。

谢谢。

1 个答案:

答案 0 :(得分:2)

当您获得$output_page时,显然只是iframe内容,请将该字符串发送到HTML解析器。像HTML::SimpleLinkExtor这样的东西可能适合你。但是,我最近一直在使用Mojo::DOM这些东西。还有&#34; How can I extract iframes from text with Perl's Mojo::DOM&#34;。

use v5.10;
use Mojo::DOM;

my $html = ...;

say "Src is ", Mojo::DOM->new( $html )->find( 'iframe' )->[0]->{src};

但是,由于您已经在使用WWW::Mechanize,因此您应该可以使用find_all_links

$mech->find_all_links( tag => 'iframe' )