WWW::MechanizeとMIME::Liteで作るメール報告ツール

2008年02月10日 written by fjkktkys

それPlaggerでと言われそうですが、かなり今更感がありますけど、Plaggerはそれなりに敷居が高い気がします。

お題はアマゾンアフィリエイトのメール報告ツールです。これを自動化する目的は、ログインから各報告ページまでのクリックなどが、個人的には面倒だなあという感じがするからです。

以下のコードのemailとpassword部分を必要なものに変えて使ってみてください。ログインして、各ページの必要な部分をdivタグごと抜き出してそれをHTMLに適当に切り貼りして(編集メンドイ)、HTMLメールにして送るというだけのものです。

正規表現の替わりにWeb::Scraperを使うのも良さそうです。

#ちなみにAmazon側でリンクのURLの順番などが替わったら、follow_linkの内容を変えないといけません。follow_linkでurlやregex_textを直接指定してもうまくいかなく、さっくり諦めました。

CODE:
  1. #!/usr/local/bin/perl
  2. use strict;
  3. use WWW::Mechanize;
  4. use MIME::Lite;
  5.  
  6.  
  7. my $url = 'https://affiliate.amazon.co.jp/gp/associates/login/login.html';
  8. my $mech = WWW::Mechanize->new(agent => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)');
  9. # login form
  10. $mech->get($url);
  11.  
  12.  
  13. # login
  14. $mech->submit_form(
  15.   form_number => 1,
  16.   fields      => {
  17.     email => 'your@email.address',
  18.     password => 'yourpassword',
  19.   },
  20. );
  21. my $total = ( $mech->content() =~ /(<div id=\"sidebar\">.*?)<div id=\"content\" class=\"withSidebar\">/s )[0];
  22. # revenue page
  23. $mech->follow_link( n => 14 );
  24. my $revenue = ($mech->content() =~ /(<div class=\"reporttext\">(.*?)<\/table>)/s)[0];
  25. # ordered page
  26. $mech->back();
  27. $mech->follow_link( n => 15 );
  28. my $ordered = ($mech->content() =~ /(<div class=\"reporttext\">(.*?)<\/table>)/s)[0];
  29. my $css = ($mech->content() =~ /(<link rel=\"stylesheet\".*?\/>)/)[0];
  30. my $html = "<html><head>$css<\/head><body>$total<hr>$revenue<hr>$ordered<\/body><\/html>";
  31. my $msg = MIME::Lite->new(
  32.     From     => 'bla@bla.bla',
  33.     To       => 'your@email.address',
  34.     Subject  => 'amazon affiliate report',
  35.     Type     => 'text/html',
  36.     Data     => $html,
  37. );
  38. $msg->send;

track feed

Leave a Reply

add to hatena hatena.comment (0) add to del.icio.us (1) add to livedoor.clip (1) add to Yahoo!Bookmark (0) Total: 2