defmodule ShopLocal.ClothingTreeSearchProvider do
import ShopLocal.SearchProvider
def search(name, s, opts \\ []) do
search_with_cache(name, s, &fetch/1, opts)
end
def fetch(s) do
case HTTPoison.get("https://www.clothes-tree.com/search?q=#{s}") do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
{:ok, document} = Floki.parse_document(body)
results = document
|> Floki.find(".main-content .product-item")
|> Enum.map(fn (k) ->
name = k
|> Floki.find(".product-item__title")
|> Floki.text
link = k
|> Floki.find("a.product-item__link")
|> Floki.attribute("href")
|> List.first
image_src = k
|> Floki.find("img.product-item__image")
|> Floki.attribute("src")
|> List.first
price = case Floki.find(k, ".product-item__meta__inner p:last-child") do
[{_tag, _attrs, price_children}] ->
price_parts =price_children
|> List.last
|> String.trim
|> String.replace("$", "") |> Float.parse
case price_parts do
{res, _} -> res
:error -> nil
end
_ -> nil
end
link = case String.starts_with?(link, "http") do
false -> "https://www.clothes-tree.com/" <> link
true -> link
end
%{
provider: "Clothes Tree",
name: name,
desc: "",
price: price,
link: link,
image_src: image_src
}
end)
|> Enum.filter(fn
%{ name: "" } -> false
_ -> true
end)
{:ok, results}
{:ok, %HTTPoison.Response{status_code: 404}} ->
{:error, "Not found." }
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, reason}
end
end
end