使用cheerio Nodejs进行Web刮痧

时间:2018-04-27 17:06:41

标签: javascript node.js web-scraping cheerio

我正试图在MonsterIndia.com上没有经验来抓取工作,所以我使用cheerio和nodejs编写了以下代码,我观察到我可以通过搜索php来搜索https://www.monsterindia.com/**php**-jobs.html个工作。 {1}}但如果我想以零经验搜索php作业,我必须在网站上手动添加过滤器,但它没有反映在页面的网址中,所以我怎样才能实现这一点,我是一个完整的初学者在网页抓取中,请帮助。

var request = require('request');
var cheerio = require('cheerio');
const context = "php";
function scraper(context){
    request('http://www.monsterindia.com/'+context+"-jobs.html", function (error, response, html) {
        if (!error && response.statusCode == 200) {
            console.log("Request Called");
            var $ = cheerio.load(html);
            var jobs = [];
            var json = {title : "", link:"", description:"", };
            $('a.title_in').each(function(i , element){


                console.log($(this).attr('title'));

            })
        } 
        if(error){
            console.log(error);
        } 

    });
}
scraper(context);

2 个答案:

答案 0 :(得分:0)

您可以使用casperjs库来实现目标。这是一个简单的示例,放在其网站上,使用Google搜索引擎搜索单词,然后获取放置在搜索结果第一页中的链接。

var links = [];
var casper = require('casper').create();

function getLinks() {
    var links = document.querySelectorAll('h3.r a');
    return Array.prototype.map.call(links, function(e) {
        return e.getAttribute('href');
    });
}

casper.start('http://google.fr/', function() {
   // Wait for the page to be loaded
   this.waitForSelector('form[action="/search"]');
});

casper.then(function() {
   // search for 'casperjs' from google form
   this.fill('form[action="/search"]', { q: 'casperjs' }, true);
});

casper.then(function() {
    // aggregate results for the 'casperjs' search
    links = this.evaluate(getLinks);
    // now search for 'phantomjs' by filling the form again
    this.fill('form[action="/search"]', { q: 'phantomjs' }, true);
});

casper.then(function() {
    // aggregate results for the 'phantomjs' search
    links = links.concat(this.evaluate(getLinks));
});

casper.run(function() {
    // echo results in some pretty fashion
    this.echo(links.length + ' links found:');
    this.echo(' - ' + links.join('\n - ')).exit();
});

答案 1 :(得分:0)

最好的方法是在cheerio中使用.filter()函数,以下是我的代码,它实现了一个这样的过滤器。

var job = $('div.job-container').filter(function (i, el) {
 var exp = $(this).children('div.view-apply- 
  container').children('div.padding-top-5').children('div.col-md- 
  3.col-xs-3.col-lg-3').children('span.experience');
  if (!exp){
      return $('div.job-container');
  }
  else{
      exp = exp.text().charAt(0) === '0';
      return exp;
  }
});