Last active
September 19, 2018 20:11
-
-
Save kitlangton/e43a9a178b2af387e08c5ad80cc3dfe2 to your computer and use it in GitHub Desktop.
Amazon Scraper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE OverloadedStrings #-} | |
module Lib where | |
import Text.HTML.Scalpel | |
import Data.Maybe (fromMaybe) | |
import Data.Char | |
import Control.Applicative | |
import Text.Read (readMaybe) | |
searchUrl :: String -> String | |
searchUrl query = "http://www.amazon.com/s/?field-keywords=" ++ query | |
data Result = Result { | |
title :: String, | |
rating :: (Maybe Float) | |
} | |
deriving Show | |
allResults :: String -> IO [Result] | |
allResults query = fromMaybe [] <$> scrapeURL (searchUrl query) results | |
where | |
results :: Scraper String [Result] | |
results = chroots ("li" @: [hasClass "s-result-item"]) result | |
result :: Scraper String Result | |
result = do | |
title <- text $ "h2" | |
rating <- optional $ text $ "i" @: [hasClass "a-icon-star"] // "span" | |
return $ Result title $ rating >>= parseRating | |
parseRating :: String -> Maybe Float | |
parseRating = readMaybe . (takeWhile $ not . isSpace) . (dropWhile $ isAlpha) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main where | |
import Lib | |
main :: IO () | |
main = do | |
putStrLn "Enter your Amazon query:" | |
results <- allResults =<< getLine | |
mapM_ printResult results | |
printResult :: Result -> IO () | |
printResult (Result item rating) = do | |
putStrLn item | |
putStrLn $ maybe "N/A" show rating | |
putStrLn "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment