0

我正在尝试使用 Enlive 从 Clojure 中的 HTML 获取链接。我可以从一个页面获取所有链接的列表吗?我可以遍历它们吗?

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')

print(soup.prettify())
# <html>
#  <head>
#   <title>
#    The Dormouse's story
#   </title>
#  </head>
#  <body>
#   <p class="title">
#    <b>
#     The Dormouse's story
#    </b>
#   </p>
#   <p class="story">
#    Once upon a time there were three little sisters; and their names were
#    <a class="sister" href="http://example.com/elsie" id="link1">
#     Elsie
#    </a>
#    ,
#    <a class="sister" href="http://example.com/lacie" id="link2">
#     Lacie
#    </a>
#    and
#    <a class="sister" href="http://example.com/tillie" id="link2">
#     Tillie
#    </a>
#    ; and they lived at the bottom of a well.
#   </p>
#   <p class="story">
#    ...
#   </p>
#  </body>
# </html>
links = soup.find_all('a')

或者

links = soup('a')

如何在 Clojure 中使用 Enlive 执行此操作?

4

2 回答 2

2

首先,您需要使用 Enlive 的html-resource功能摄取一些 HTML。我们将抓取 news.google.com:

(defn fetch-url [url]
  (html/html-resource (java.net.URL. url)))
(def goog-news (fetch-url "https://news.google.com"))

要获取所有<a>标签,请使用select带有简单选择器(第二个参数)的函数:

(html/select goog-news [:a])

这将评估为一系列地图,每个<a>标签一个。<a>这是今天新闻中的示例标签映射:

{:tag :a,
 :attrs {:class "nuEeue hzdq5d ME7ew",
         :target "_blank",
         :href "https://www.vanityfair.com/hollywood/2018/01/first-black-panther-reviews",
         :jsname "NV4Anc"},
 :content ("The First Black Panther Reviews Are Here—and They're Ecstatic")}

要获取每个 的内部文本<a>,您可以在结果上使用mapEnlive 的text功能,例如 (map html/text *1). 得到每一个href,就可以了(map (comp :href :attrs) *1)

于 2018-02-05T13:13:28.287 回答
1

那将非常简单:

(require '[net.cgrand.enlive-html :as enlive])

(let [data (enlive/html-resource (java.net.URL. "https://www.stackoverflow.com"))
      all-refs (enlive/select data [:a])]
  (first all-refs))

;;=> {:tag :a, :attrs {:href "https://stackoverflow.com", :class "-logo js-gps-track", :data-gps-track "top_nav.click({is_current:true, location:1, destination:8})"}, :content ("\n                   " {:tag :span, :attrs {:class "-img"}, :content ("Stack Overflow")} "\n                ")}

all-refs集合将包含来自页面的所有链接,以活跃的表示形式。

(let [data (enlive/html-resource (java.net.URL. "https://www.stackoverflow.com"))
      all-refs (enlive/select data [:a])]
  (map #(-> % :attrs :href) all-refs))

例如会href从链接中收集所有值

于 2018-02-05T13:11:12.580 回答