npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

shears

v0.0.0-alpha.92

Published

Functional web scraping in typescript

Downloads

2

Readme

Shears

A Declarative web scraping library that aims to provide an extendable set of tools for building complex typesafe queries and web crawlers.

import * as sh from 'shears'

const article = sh.select({
    title: sh.select('h1', sh.text),
    content: sh.select('h1', sh.text)
    image: sh.select('img', sh.atr('src'))
})

const article_list = sh.select('#content', ['ul > li'], article)

await sh.runP(article_list, '<html><...')
// [{ title: '...' content: '...' },{...]

The library works best when used in combination with fp-ts however the runP returns a Promise instead of TaskEither returned by the run function, this allows for standalone use but still requires fp-ts as a peer dependency.

Usage

Selectors

The select function is the main building block and can be used for chaining selectors of type string, [string], Shear<Node, Node> where the final argument can be of type Shear<Node, T>.

sh.select('body > h1') // Shear<Node | Node[], Node<h1>>
sh.select('body > h1', 'span') // Shear<Node | Node[], Node<span>>
sh.select('body > ul', ['li']) // Shear<Node | Node[], Node<li>[]>
sh.select(['body > ul'], sh.text) // Shear<Node | Node[], string[]>
sh.select(['body > ul'], ['li'], sh.text) // Shear<Node | Node[], string[][]>
sh.select({ foo: sh.text }) // Shear<Node | Node[], { foo: string }>
sh.select([sh.text, sh.text]) // Shear<Node | Node[], [string, string]>
  • string: Accepts a css query and returns the first matching DOM node, like document.querySelector.
  • [string]: Accepts a css query and returns all matching DOM nodes like document.querySelectorAll.

Each query in the list of arguments operates on the part of the DOM returned by the previous query where parameters after [string] queries operate on each item in the return list.

select can also be used for creating structured queries where it takes a single argument of type { [x: string]: Shear<Node, T> } or Shear<Node, Node>[].

sh.select({ title: sh.select('title') }) // Shear<Node | Node[], { title: Node<title> }>
sh.select([sh.select('title'), sh.select('h1')] as const) // Shear<Node | Node[], [Node<title>, Node<title>]>

customizing Shears

A "Shear" extends the ReaderTaskEither type class so you can easily build your selectors.

import { map } from 'fp-ts/ReaderTaskEither'
import { pipe } from 'fp-ts/function'

import sh, { run } from 'shears'

const trimText = pipe(
  sh.text,
  map((y) => y.trim())
)

run(sh('body > h1', trimText), `<h1> foo </h1>`) // TaskEither<never, 'foo'>

Crawling

The library provides a few shears to help with queries across multiple pages.

import { map } from 'fp-ts/ReaderTaskEither'
import { pipe } from 'fp-ts/function'
import axios from 'axios'

import * as sh from 'shears'

const connection = sh.connect((url) => axios.get(url).then((x) => x.data))

sh.run(
  sh.select({
    posts: sh.select(
      '[#post]',
      sh.goTo(
        sh.select('a', sh.atr('href')),
        sh.select({
          title: sh.select('h1', sh.text)
        }),
        { connection }
      )
    )
  })
)

Often it is the case you want to follow relative links on a website where our connection would need to know the current hostname. The "Shear" provides a mechanism for passing context we just need to change the connection implementation.

const connection = sh.connect(
  (url, ctx) =>
    (/^http/.test(url) ? axios.get(url) : axios.get(ctx.hostname + url)).then((x) => [
      x.data,
      { hostname: x.response.hostname }
    ]), // We return a tuple [{  html string  },  { new context }]
  { hostname: '' } // Initial context state
)

We can pass our connection into the run function which provides it in the shear context so we don't need to pass it to goTo.

sh.run(
  sh.goTo(
    'http://foo.bar',
    sh.select({
      posts: sh(
        '[#post]',
        sh.goTo(
          sh.select('a', sh.atr('href')),
          sh.select({
            title: sh.select('h1', sh.text)
          })
        )
      )
    })
  ),
  { connection }
)