Haskell is a functional programming language that can also be used for web scraping. Although it may not be as popular as Python or JavaScript for web scraping, Haskell offers strong typing, parallelism, and purity, which can be beneficial in certain web scraping scenarios.
To perform web scraping in Haskell, you can use libraries like http-conduit for making HTTP requests and html-conduit or tagsoup for parsing HTML.
Here's a step-by-step guide for web scraping in Haskell:
-
Install Haskell Stack, if you haven't already: https://docs.haskellstack.org/en/stable/README/
-
Create a new directory for your project and navigate to it in the terminal:
mkdir haskell_scraper
cd haskell_scraper
- Initialize a new Haskell Stack project:
stack new haskell_scraper simple
cd haskell_scraper
- Open the
stack.yaml file and add the following libraries under the extra-deps section:
extra-deps:
- http-conduit-2.3.8
- html-conduit-1.3.2.1
- tagsoup-0.14.8
- Open the
haskell_scraper.cabal file and add the following libraries under the build-depends section:
build-depends: base >=4.7 && <5
, http-conduit
, html-conduit
, tagsoup
- Replace the content of
src/Main.hs with the following Haskell code:
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Network.HTTP.Conduit
import qualified Data.ByteString.Lazy.Char8 as L8
import Text.HTML.TagSoup
fetchURL :: String -> IO L8.ByteString
fetchURL url = do
manager <- newManager tlsManagerSettings
request <- parseRequest url
response <- httpLbs request manager
return $ responseBody response
parseLinks :: L8.ByteString -> [String]
parseLinks content = [x | TagOpen "a" attrs <- parseTags content, (_, x) <- attrs, x /= "#"]
main :: IO ()
main = do
putStrLn "Enter the URL to scrape:"
url <- getLine
putStrLn "Fetching links..."
content <- fetchURL url
let links = parseLinks content
putStrLn "Links found:"
mapM_ putStrLn links
- Build and run the Haskell web scraper:
stack build
stack run
This simple Haskell web scraper will fetch the content of a given URL, parse the HTML, and extract the links. While this example doesn't cover more advanced features like recursion and avoiding already visited hostnames, it can be a starting point for web scraping in Haskell. You can further refine and expand the code to fit your specific web scraping requirements.