admin管理员组文章数量:1323678
I'm trying to zero in on the URL contained within the li tags on the page in my URL variable. It should be simple, but I can't get it to work. I get the correct number of elements, but they are all blank. text() returns '' & html() returns null. What am I doing wrong here?
const cheerio = require('cheerio');
const request = require('request');
function getHistory(){
let url = '/';
request(url,(error,response,html)=>{
var $ = cheerio.load(html);
$('li.text-center').each((i,element)=>{
var omg = $(this).html();
console.log(omg);
});
});
}
I'm trying to zero in on the URL contained within the li tags on the page in my URL variable. It should be simple, but I can't get it to work. I get the correct number of elements, but they are all blank. text() returns '' & html() returns null. What am I doing wrong here?
const cheerio = require('cheerio');
const request = require('request');
function getHistory(){
let url = 'http://coinmarketcap./historical/';
request(url,(error,response,html)=>{
var $ = cheerio.load(html);
$('li.text-center').each((i,element)=>{
var omg = $(this).html();
console.log(omg);
});
});
}
Share
asked Jul 15, 2017 at 2:09
RavenRaven
69913 silver badges33 bronze badges
2 Answers
Reset to default 9Because this code is in an arrow function (which retains the lexical value of this, not what .each()
sets it to), the value of this
is not set to what you want it to be. If you change this:
var omg = $(this).html();
to this:
var omg = $(element).html();
You will see the HTML you were expecting.
Note, you may also be able to change the arrow function to a regular function and then whatever value of this
that .each()
sets will be in effect.
If what you really want is the href
, then you should target the <a>
tag with your selector and get the actual href
attribute from it. You could do that like this:
function getHistory(){
let url = 'http://coinmarketcap./historical/';
request(url,(error,response,html)=>{
let $ = cheerio.load(html);
$('li.text-center a').each((i,element)=>{
let omg = $(element).attr('href');
console.log(omg);
});
});
}
That’s because you are referring to this
in an arrow function, which doesn’t make its own this
.
本文标签: javascriptNodeJS Cheerio Scraping li tags always returns NULLStack Overflow
版权声明:本文标题:javascript - NodeJS Cheerio Scraping li tags always returns NULL - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742143927a2422704.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论