What methods can I use to integrate Cheerio with CSS Manipulation?

I've been working on a web scraping project using axios, cheerio, and express. However, every time I attempt to run the project, it encounters errors.

For testing purposes, I am using a test page from my friend's website. Here is the code snippet I used:

const express = require('express')
const app = express()
const port = 3000
const publicDir = app.use(express.static('public'))
var cheerio = require('cheerio'); // A jQuery-like tool for node.js
const { replaceWith } = require('cheerio/lib/api/manipulation');
const axios = require('axios').default;


app.get('/', (req, res) => {
  res.render('/public/index.html')
})

app.get('/imagineoranges', (req, res) => {
  const $ = cheerio.load('/imagineoranges')
  axios.get("https://imagineoranges.neocities.org")
    .then(({data}) => res.send(data))
    .then( $('a:link').css("color: white;") )
    .then( $('a:visited').css("color: yellow;") )
    .then( $('a:hover').css("color: yellow;") )
    .then( $('body').css("@import url('https://fonts.googleapis.com/css2?family=Rubik&display=swap'); background-color: #ff7300; color: white; font-family: 'Rubik', sans-serif;") ) 
})


app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

However, when you run this code, the following error occurs:

node:internal/modules/cjs/loader:535
      throw e;
      ^

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/api/manipulation' is not defined by "exports" in /home/lucas/Desktop/UBlock/node_modules/cheerio/package.json
    at new NodeError (node:internal/errors:393:5)
    at throwExportsNotFound (node:internal/modules/esm/resolve:292:9)
    at packageExportsResolve (node:internal/modules/esm/resolve:602:3)
    at resolveExports (node:internal/modules/cjs/loader:529:36)
    at Module._findPath (node:internal/modules/cjs/loader:569:31)
    at Module._resolveFilename (node:internal/modules/cjs/loader:981:27)
    at Module._load (node:internal/modules/cjs/loader:841:27)
    at Module.require (node:internal/modules/cjs/loader:1061:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/home/lucas/Desktop/UBlock/index.js:6:25) {
  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
}

Node.js v19.0.1

Answer №1

Make sure to pass the response HTML to Cheerio for manipulation before rendering it back to the user.

If you're looking to apply styles, consider using CSS instead by including a <style> tag.

Here is an example:

app.get("/oranges", async (req, res) => {
  try {
    const { data } = await axios.get("https://example.com", {
      responseType: "text",
    });
    const $ = cheerio.load(data);
    $("head").append(
      `<style type="text/css">@import url(https://fonts.googleapis.com/css2?family=Roboto&display=swap);a:link,body{color:#000}a:hover,a:visited{color:#00f}body{background-color:#ccc;font-family:Roboto,sans-serif}<style>`
    );
    res.set("content-type", "text/html").send($.root().html());
  } catch (err) {
    res.status(err.response?.status ?? 500).send(err.response?.data);
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to concatenate values from Object in JavaScript

Although it may seem trivial, the following code is giving me trouble: window.temp1.targetInterests It gives me back: Object {Famosos: "Famosos", Musica: "Música", Humor: "Humor"} I attempted to join it: window.temp1.targetInterests.join('/&apos ...

Issue with uniqueness constraint in MongoDB and Mongoose causing Unique:true to not function correctly

Within my node application, I have a user.js model where I am trying to ensure that the username and a few other fields are unique. In my model file, I have correctly specified the unique type as shown below: // User Schema const UserSchema = new Schema({ ...

Executing a save function in the controller when the TinyMCE save button is clicked through an Angular directive

For the Rich text editing in my angularjs application, I am using the TinyMce angular directive. The directive is working perfectly as expected. However, I wanted to include the save plugin to enable custom save functions. To integrate the save plugin, I ...

What is the process for submitting a post request with custom fields to the Wordpress rest api?

Currently, I am attempting to make a post request to /wp-json/wp/v2/posts while also including custom fields. However, it seems that although the request field is successfully being sent, the custom fields are not updating with the data I am trying to send ...

Experiencing inaccuracies in Magento's item validation process when checking the quantity of items being added to the cart

Upon entering a text string in the quantity field of the "Add to Cart" input box, Magento does not display an error message but instead considers it as a quantity of "1". Is there a way to modify this behavior and have the validation system mark strings ...

Is there a way to bring in both a variable and a type from a single file in Typescript?

I have some interfaces and an enum being exported in my implementation file. // types/user.ts export enum LoginStatus { Initial = 0, Authorized = 1, NotAuthorized = 2, } export interface UserState { name: string; loginStatus: LoginStatus; }; ex ...

Ways to restrict a JavaScript object from being sent through ajax requests

I have developed an application that utilizes JSON to send messages through ajax. Here is the JavaScript object used for this purpose: var message = { "message_by": colmn[0].innerHTML, "message_date": new Date(), "message_recipients": [ { ...

What could be causing the Toast message to not show up in react-native-root-toast?

Incorporated react-native-root-toast into my expo project running on expo 51. Please see the code snippet below for reference: const toastColors = { 'error': { color: '#DA5C53', iconName: <WarningIcon size="5 ...

A dynamic AJAX menu showcasing content in a dropdown format, away from the conventional table layout

My dropdown select menu is correctly populating with data, but the output always appears outside of the table. Can anyone spot the issue in my code? Any suggestions or ideas are greatly appreciated! Thanks in advance, select.php <?php $q = $_GET[&apos ...

The process of parsing dates with MomentJS functions correctly for two dates, however, it displays 'Invalid Date' for the third date

I've tried over 50 solutions from Stack Overflow posts, but nothing seems to be working for me. I have three dates: Date 1: 2018-10-28T17:21:38Z Date 2: 2020-10-28T22:29:30Z Date 3: 2021-10-28T17:21:38Z Attempting to parse them into readable formats. ...

The Material-UI Snackbar stubbornly refuses to disappear even after setting its controlled state to false

I am currently working with a Snackbar component that relies on the redux state for control. I have implemented the onRequestClose() function in an attempt to disable the clickaway close feature. However, I have encountered an issue where setting the prop ...

JavaScript text converter using split() method

I have a large amount of data in text format, similar to the following: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e0b0d1b0c1b131f17124f3e19131f1712501d1113">[email protected]</a>:token1 | Time = US | Alphabe ...

What is the best way to showcase information from multiple JSON files simultaneously?

Creating dynamic JSON URLs based on browser cookie data. var cookie = $.cookie('faved_posts'); The cookie contains IDs like 123456, 111111, 000001, etc. Now we need to request the JSON file for each ID in the cookie. We have: $.each(cookie, ...

Executing the fs.readFile operation within the callback of its parent fs.readFile does not happen asynchronously

I recently learned about the asynchronous nature of fs.readFile, where the reading process happens in a separate thread allowing the main thread to continue without being blocked. Intrigued by this concept, I decided to experiment with the following code s ...

Is req.params in Express 3.x represented as an object enclosed in square brackets?

My POST handler code includes: app.use(express.bodyParser()); app.use(app.router) app.post('/api/auth/:service', function(req, res) { console.log('req.params', req.params); ... Upon printing req.params, I notice something unusual ...

How can we showcase the data within this loop on the user interface in React JS?

I'm currently working with React JS and I have a question regarding how to display data from a loop in the UI. The code snippet below shows the data being logged to the console, but I want to show it on the actual user interface. Could you please guid ...

Cloudflare SSL Error 522 Express: Troubleshooting Tips for Res

After setting up my express project using express-generator, I decided to make it work with a cloudflare SSL Certificate for secure browsing over https. My express app is running on port 443. Despite my efforts, when I try to access the domain, I encount ...

Is npm bundled with node-gyp?

I am currently experiencing an issue where running npm install locally does not produce much output when using npm v6.14.9. However, when I deploy to the server, it generates some incomprehensible messages like: gyp info spawn args ['some properties a ...

Having trouble with closing the window on Mozilla and Chrome? Keep getting a scripting error message?

To close this window, click <a onclick="self.close();" href="#">here</a>. This is the code I am using. When I submit in Chrome and Mozilla, an error occurs. The error message is: "Script must not be allowed to close a window that was not o ...

Does the triple equal operator in JavaScript first compare the type of the value?

When using the triple equal operator, it not only measures the value but also the type. I am curious about the order in which it compares the value and returns false if they do not match, or vice versa. ...