nodejs get an url content and find for title text
- User
nodejs get an url content and find for title text
- Assistant
To get the content of a URL and find the title text using Node.js, you can use the
axioslibrary for making HTTP requests and thecheeriolibrary for parsing HTML.Here's an example code snippet that shows how to do this:
const axios = require('axios'); const cheerio = require('cheerio'); const url = 'https://example.com'; // Replace with your desired URL axios.get(url) .then(response => { const html = response.data; const $ = cheerio.load(html); const title = $('title').text(); console.log('Title:', title); }) .catch(error => { console.log('Error:', error); });Make sure to install the required dependencies by running the following command before running the above code:
npm install axios cheerioThis code sends an HTTP GET request to the specified URL (
https://example.comin this example). Once the response is received, the HTML content is extracted from the response data. Thecheeriolibrary is then used to parse the HTML. In this case, we look for the<title>element and retrieve the text within it using thetext()method.Finally, the title text is logged to the console.