java - 在 Clojure 中使用 JSoup 解析字符串

用JSoup用Clojure解析html字符串,源码如下

依赖

:dependencies [[org.clojure/clojure "1.10.1"]
               [org.jsoup/jsoup "1.13.1"]]

源代码

(require '[clojure.string :as str])
(def HTML (str "<html><head><title>Website title</title></head>
                <body><p>Sample paragraph number 1 </p>
                      <p>Sample paragraph number 2</p>
                </body></html>"))

(defn fetch_html [html]
  (let [soup (Jsoup/parse html)
        titles (.title soup)
        paragraphs (.getElementsByTag soup "p")]
    {:title titles :paragraph paragraphs}))

(fetch_html HTML)

预期结果

{:title "Website title", 
 :paragraph ["Sample paragraph number 1" 
             "Sample paragraph number 2"]}

很遗憾,结果并不如预期

user ==> (fetch_html HTML)
{:title "Website title", :paragraph []}

最佳答案

(.getElementsByTag ...) 返回一个元素序列,您需要在每个元素上调用 .text() 方法来获取文本值。我正在使用 Jsoup 版本 1.13.1。


(ns core
  (:import (org.jsoup Jsoup))
  (:require [clojure.string :as str]))

(def HTML (str "<html><head><title>Website title</title></head>
                <body><p>Sample paragraph number 1 </p>
                      <p>Sample paragraph number 2</p>
                </body></html>"))

(defn fetch_html [html]
  (let [soup (Jsoup/parse html)
        titles (.title soup)
        paragraphs (.getElementsByTag soup "p")]
    {:title titles :paragraph (mapv #(.text %) paragraphs)}))

(fetch_html HTML)

还可以考虑使用 Reaver,它是一个包装 JSoup 的 Clojure 库,或者像其他人建议的任何其他包装器。

https://stackoverflow.com/questions/65591867/

相关文章:

awk - 将 awk 应用于除第一行以外的所有内容

arrays - 加起来等于一个数的组合 - Julia lang

c++ - 如何在 QPixmap 中旋转照片?

haskell - 如何在特定情况下使用高阶结构

postgresql - 通过 DBeaver 添加列时,Hasura (Graphql) 控制台中

deep-learning - 如何通过一次操作合并两个 torch.utils.data 数据加载

javascript - 如果 "any"不能在 Nest.js 中使用,模式中的字段类型应该是什么

powershell - 无法注册 PS 图库

python - 如果删除包含另一个对象的对象会怎样?

c# - 将 RestSharp 用于以下代码的内置替代方法是什么?