Access to DOM using node.js

半腔热情 提交于 2019-12-05 10:09:05

cheerio.load() accepts a string as the argument. By setting: cheerio.load('file.html') cheerio will try to implement DOM from the string file.html. Obviously, that is not what you want.

You should get the html data from your file first, then pass it to the cheerio. Also as @Quentin metioned, cheerio is a cut down implementation of jQuery, so you should use jQuery selectors to get a ceratin element. For your particular case it would be: $("#GraphImage"). Here is how your code should look like:

 var cheerio = require('cheerio'),
     $ = cheerio.load('file.html'),
     fs = require('fs');
 fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err; 
    } else {
        $ = cheerio.load(html.toString());
        console.log($('#GraphImage').attr('src'));   
    }

EDIT:

Also, in the html file that you have provided, you are appending some objects to the DOM with the help of javascript. If you want to access them on the server, the javascript should be interpreted there. You can use something like phantomjs to achieve it, but things get much more complicated.

silverfighter

It looks like your mixing client side and server side javascript.

but to answer your question you can access the src in the following way:

 var src = $('#GraphImage').attr("src");

make sure you first load your html file with fs

// EDIT: Your are getting 'undefined' because the img tag is dynamically generated and not present at the moment you are loading the file with node on the server. That's what I meant your are mixing client code with server side code. You might want to grab the diagramContainer $('#diagramContainer') and add an image tag inside it and set the source. $('#diagramContainer').prepend('<img id="theImg" src="theImg.png" />')

If you have a path you can set it directly if you generate the png on the server an have a binary stream things can get more tricky.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!