HTML を処理する - lisp-cookbook-ja/common-lisp GitHub Wiki

インターネットサービス HTML

HTML を処理する

HTML から必要な情報を抜き出すためのライブラリは様々ありますが、下記では、CLiki:closure-htmlを使用しています。

drakma:http-requestでWilikiのページ一覧を取得し

  • の項目の数を数える
    (defun count-pages (url)
      (let* ((page (drakma:http-request url))
             (doc (chtml:parse page (cxml-stp:make-builder)))
             (ans 0))
        (stp:do-recursively (a doc)
          (when (and (typep a 'stp:element)
                     (equal (stp:local-name a) "li"))
            (incf ans)))
        ans))
    
    ;; 試してみる
    (mapcar #'count-pages
            '("http://practical-scheme.net/wiliki/wiliki.cgi?c=a"
              "http://tips.lisp-users.org/common-lisp/index.cgi?c=a"
              "http://tips.lisp-users.org/scheme/index.cgi?c=a"))
    ;=>(942 202 114)

    drakma:http-requestでWilikiのページ一覧を取得し

  • の項目の中の文字列を取得する
    (defun all-items (url)
      (let* ((page (drakma:http-request url))
             (doc (chtml:parse page (cxml-stp:make-builder)))
             (ns (stp:namespace-uri (stp:document-element doc))))
        (mapcar #'stp:string-value
                (stp:filter-recursively (stp:of-name "li" ns) doc))))
    
    ;; 逆引きSchemeに存在して 逆引きCLに存在しない項目をリストにする
    (let ((p1 (all-items "http://tips.lisp-users.org/common-lisp/index.cgi?c=a"))
          (p2 (all-items "http://tips.lisp-users.org/scheme/index.cgi?c=a")))
      (set-difference p2 p1 :test #'string=))
    ;=> ("CGI を作る" "CPUのエンディアンを調べる" ...)
  • ⚠️ **GitHub.com Fallback** ⚠️