プロが教える店舗&オフィスのセキュリティ対策術

perlでHTMLソースを解析してformタグの要素を取得したいのですが、そのようなライブラリはありますか?
できれば、javascriptでHTMLソースから情報を得られるようなAPIだと良いのですが。
即ち、document.forms[].actionとかdocument.forms[].elements[].valueのように。

A 回答 (2件)

私ならMechanizeを使いますが。


他の方の書き込みも美しいですなぁ。

WWW-Mechanize
http://search.cpan.org/~petdance/WWW-Mechanize-1 …


#!/usr/bin/perl
use strict;
use WWW::Mechanize;
use encoding 'utf8';

my $mech = WWW::Mechanize->new;
$mech->get("http://www.google.co.jp/");

for my $form($mech->forms){
 printf("%s %s\n", $form->method, $form->action);

 my @names = $form->param;
 for(@names){
  printf(" %s => %s\n", $_, $form->param($_));
 }
 
 print "\n";
}
    • good
    • 1
この回答へのお礼

ありがとうございます。
これ使えそうです。

お礼日時:2010/10/02 17:27

やり方は色々あるんですが、HTML::TagParserを使う方法を書きます。


表示がずれるので、空白2文字を全角空白にしてます。
use strict;
use warnings;
use HTML::TagParser;

my $page = << 'EOT';
<html>
 <head>
  <title>The Title</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
 </head>
 <body>
  <hr />
  <form id="form1" method="get" action="print_env1.cgi">
   <input type="text" name="username" value="Anonymous" /><br />
   <input type="submit" name="Send" value="Send" />
  </form>
  <form id="form2" method="post" action="print_env2.cgi" enctype="multipart/form-data">
   <input type="text" name="username" value="Anonymous" /><br />
   <input type="submit" name="Send" value="Send" />
  </form>
 </body>
</html>
EOT

my $html = HTML::TagParser->new($page);
my @forms = $html->getElementsByTagName('form');

for my $elem (@forms) {
  my $tagname = $elem->tagName;
  my $attr  = $elem->attributes;
  my $text  = $elem->innerText;

  print "--- tagname", $/, $tagname, $/;
  print "--- attribute", $/;
  for my $key ( sort keys %{$attr} ) {
    print "$key=", $attr->{$key}, $/;
  }
  print "--- interText", $/, $text, $/;
}

# result
#
# --- tagname
# form
# --- attribute
# action=print_env1.cgi
# id=form1
# method=get
# --- interText
#
# --- tagname
# form
# --- attribute
# action=print_env2.cgi
# enctype=multipart/form-data
# id=form2
# method=post
# --- interText
#
    • good
    • 0
この回答へのお礼

ありがとうございます。
参考にしてみます。

お礼日時:2010/10/01 07:54

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!