Created
June 16, 2013 14:23
-
-
Save kencharos/5792225 to your computer and use it in GitHub Desktop.
アンパンマンのサイトからキャラクター一覧を引っ張って適当なHTMLにする。
あとは関数型プログラム、関数合成の練習 .
run に保存したいファイル名を渡して実行する。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.io.Source | |
import scala.xml._ | |
/** アンパンマンのサイトからキャラクター一覧を引っ張って適当なHTMLにする。 | |
あとは関数型プログラム、関数合成の練習 */ | |
object AmpFriends { | |
case class Friend(name:String, img:String) | |
val base ="http://anpanman.jp/sekai/" | |
val imgBase ="http://anpanman.jp/sekai/friends/" | |
val loadFromUrl:String => String = Source.fromURL(_).mkString | |
val mainContent:String => Elem = { | |
loadFromUrl andThen ((html:String) => { | |
val start = html.indexOf("""<div id="contentsArea""") | |
val end = html.indexOf("""<!-- InstanceEndEditable -->""",start) | |
XML.loadString(html.substring(start, end)) | |
}) | |
} | |
val mkIndex = (xml:Elem) => { | |
val list = xml \\ "div" filter{n => (n \\ "@class").text == "nakamalist"} | |
val link = list \\ "li" map{n => base + (n \\ "a" \\ "@href").text} | |
link.filter(_ endsWith(".html")) | |
} | |
val getChatacter = (xml:Elem) => { | |
xml \\ "li" \\ "img" map {n => Friend((n \\ "@alt").text, imgBase + (n \\ "@src").text)} | |
} | |
//http://anpanman.jp/sekai/friends/images/akachan_sn.gif | |
val getAll = (url:String) => { | |
val list = mainContent andThen mkIndex | |
val get = mainContent andThen getChatacter | |
list(url) flatMap{u => println("load "+ u); get(u)} | |
} | |
def run(file:String) = { | |
val list = getAll("http://anpanman.jp/sekai/friend.html") | |
val start = """<!DOCTYPE html> | |
<html> | |
<head> | |
<style type="text/css"> | |
ul {list-style: none;} | |
ul li {display: list-item;border:1px solid black; float: left; width:200px;} | |
ul li span{width:110px;display:inline-block;} | |
ul li img {max-width: 80px} | |
</style> | |
</head> | |
<body><ul> | |
""" | |
val end = """</ul></body></html>"""; | |
val result = list.map{n => "<li><span>" + n.name + "</span><img src='" + n.img +"'/></li>"} | |
import java.io.PrintWriter | |
val out = new PrintWriter(file) | |
out.println(start) | |
result.foreach(out.println) | |
out.println(end) | |
out.close | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment