Home > Software design >  How to get backgroundImage url in cheerio
How to get backgroundImage url in cheerio

Time:01-06

I was trying to get banner of my Anime-Planet account for my scraper system. I tried everything i have know with cheerio but i couldn't get the profileBackgrounds background-image url. Properties

I tried

async function Al() {
  const cheerio = require("cheerio");
  const url = "https://www.anime-planet.com/users/kyoyacchi";
  const {data} = await client.axios.get(url, {
    headers: {
      "User-Agent":
        "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Mobile Safari/537.36",
    },
  });
  const $ = cheerio.load(data);

  return $(".pull-beta.pull-alpha.pullup.editableBanner")
    .find(".wrapper")
    .find("profileBackground");
}
Al();

Here is the result

This one is only returns avatar path.

CodePudding user response:

I learned that it's $('div[id=profileBackground]')

CodePudding user response:

You can retrieve the image path with:

axios.get(url)
  .then(({data: html}) => {
    const $ = cheerio.load(html);
    const path = $("#profileBackground")
      .attr("style")
      .match(/background-image: *url *\((. ?)\)/)[1];
    console.log(path); // => /images/users/backgrounds/3966485.jpg?t=1660418964
  });

Use #some-id to select by the id attribute. In CSS, a bare word refers to a tag name, so p is the selector for <p></p>. Ids are supposed to be unique in the document, so you don't usually need to specify parent selectors.

The regex above extracts the contents from the parentheses after background-image: url.

  • Related