iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
✂️

Migrating from cheerio to puppeteer for Local File Scraping

に公開

When I perform scraping for light analysis, I usually follow these steps:

  1. Generate a list of required pages through various means.
  2. Fetch the list using wget or curl (using $ wget -i list.txt is convenient).
  3. Process the local files with iconv-lite and cheerio.

While many people scrape while crawling simultaneously, I personally recommend separating the crawling and actual scraping. This is because retrying upon processing errors or deciding to extract additional values later is not uncommon.

For example, if you want to extract values from a table in an HTML file, it looks like this:

const cheerio = require("cheerio")
const iconv = require("iconv-lite")

const file = fs.readFileSync("./file.html")
const ff = iconv.decode(file, "ShiftJIS").toString()
const $ = cheerio.load(ff)
let trs = []
$("table tr").each(function (_, tr) {
let tds = []
  $(tr).children("td").each(function (_, td) {
    tds.push($(td).text().trim())
  })
  trs.push(tds)
})

The appeal of cheerio was its jQuery-like syntax, but since I haven't touched jQuery in a long time, I'm starting to forget it. Furthermore, having to use each for processing when I'd rather use something like map increased my desire to move away from it.

Leaving everything to Puppeteer

I have naturally used Puppeteer here and there, but my impression was that it was mostly for rich use cases like E2E testing and not particularly suited for processing local files.

However, upon investigation, I found information suggesting that I could process local files using setContent.

https://stackoverflow.com/questions/47587352/opening-local-html-file-using-puppeteer/52789802#52789802

When you use it, it looks like this:


const file = fs.readFileSync("./file.html")
// I actually wanted to leave iconv to puppeteer as well, but gave up as it seemed a bit difficult
const encoded = iconv.decode(file, "ShiftJIS").toString()

// Set up the browser
const browser = await puppeteer.launch()
const page = await browser.newPage()
// Set the page
await page.setContent(encoded.toString())

// Scraping
const table = await page.$("table")
const trs = await table.$$("tr")
const data = await Promise.all( trs.map(async tr => {
  return await tr.$$eval("td", (nodes) => {
    // This part inside the closure is executed on the Chrome side
    return nodes.map(node => node.innerText)
  })
}))
browser.close()

A small point to watch out for is that the inside of $$eval is executed on the Chrome side (similarly for $eval and evaluate). Therefore, any console.log() inside here will naturally not be displayed on the Node.js side.

If you want to debug, it's easy to check by doing the following:

const browser = await puppeteer.launch({
  headless: false,
  devtool: true
})

Discussion