elixir 新手,我只找到了两种运行代码的方法。想知道是否有更好的方法:
Module_name.function_name()
打开交互式外壳并通过调用仅运行该函数的模块在模块内运行一个或多个函数如果我想运行整个模块,那么我打开交互式 shell,必须将模块中的所有代码粘贴到 shell 中,然后点击
enter
我确信这很明显,但我在任何地方都找不到任何令人满意的答案。刚刚使用此模块尝试了选项 #2,它在应该返回评论列表时返回了这个。谢谢。
defmodule KgbScrape do
use HTTPoison.Base
@endpoint "https://www.dealerrater.com/dealer/McKaig-Chevrolet-Buick-A-Dealer-For-The-People-dealer-reviews-23685/page"
def build_urls() do
page_num = ["1","2","3","4","5"]
tail_url = ["/?filter=#link"]
for page <- page_num, tail <- tail_url do
urls_list = @endpoint <> page <> tail
end
end
def fetch_pages(url) do
url
|> HTTPoison.get()
|> response()
end
def process_pages(urls_list) when is_list(urls_list) do
resp =
urls_list
|> Task.async_stream(fn url -> fetch_pages(url) end)
|> Enum.map(fn {_, resp} -> resp end)
Enum.map(resp, fn r ->
r
|> Floki.parse_document!()
|> Floki.find(".review-entry")
|> Map.new(fn entry ->
[{"div", _, [date]}] = Floki.find(entry, "div.italic")
[{"p", _, [content]}] = Floki.find(entry, "p.review-content")
{date, content}
end)
end)
end
def response({:ok, %{body: {:ok, %{"error" => error}}}}) do
{:error, error}
end
def response({:ok, %{body: body}}), do: body
def response({:error, error}), do: {:error, error}
end
结果是:
warning: redefining module KgbScrape (current version loaded from _build/dev/lib/kgbScrapeApp/ebin/Elixir.KgbScrape.beam)
iex:7
warning: variable "urls_list" is unused (if the variable is not meant to be used, prefix it with an underscore)
iex:15: KgbScrape.build_urls/0
{:module, KgbScrape,
<<70, 79, 82, 49, 0, 0, 68, 252, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0,
5, 107, 0, 0, 0, 103, 16, 69, 108, 105, 120, 105, 114, 46, 75, 103,
98, 83, 99, 114, 97, 112, 101, 8, 95, 95, 105, 110, 102, ...>>,
{:response, 1}}