Cheerio keeps returning undefined for attr of element
See original GitHub issueHi there. I don’t know if this is a bug or a mistake from my end, but the following line keeps returning ‘undefined’.
const request = require('axios');
getImage(link) {
return new Promise((resolve, reject) => {
request
.get(link)
.then((response) => {
let html = response.data;
let $ = cheerio.load(html);
let image = $('img.vacancy-img').attr('src');
return resolve(image);
})
.catch((error) => reject(error));
});
}
HTML: http://topjobs.lk/employer/advertismentpreview.jsp?jc=0000450465&rid=39&ac=DEFZZZ&ec=DEFZZZ
Using jquery on the site, the function returns the expected data, but not via cheerio.
Issue Analytics
- State:
- Created 6 years ago
- Comments:5 (2 by maintainers)
Top Results From Across the Web
Cheerio returns undefined when calling .each() on elements
I need to get all the "href" attribute of all the elements with class ".thumb" . I'm showing the results on the console...
Read more >cheerio.src JavaScript and Node.js code examples - Tabnine
const imageAttr = $('.keteranganinside img').attr(); const imageUrl = (imageAttr === undefined) ? null : imageAttr.src;
Read more >api documentation for cheerio (v0.22.0)
contains = function (container, contained) { // According to the jQuery API, an element does not "contain" itself if (contained === container) {...
Read more >.contents() | jQuery API Documentation
This DOM property holds a numeric code indicating the node's type; text nodes use the code 3. The contents are again filtered, this...
Read more >4 Tools for Web Scraping in Node.js - Twilio
const isMidi = (link) => { // Return false if there is no href attribute. if(typeof link.href === 'undefined') { return false }...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Looking at the link you provided, the image you’re targeting is loaded dynamically. I would guess that at the time you’re trying to access it’s
src
, it hasn’t been loaded.I would suggest adding a delay loop that checks if the image exists.
Note: The image doesn’t load as a dataURI. The one on the page you linked first appears like this:
This means you have to check for not only the existence of the image, but some other check like a minimum length of the
src
attribute.What @MCTaylor17 said 😃