使用 cheerio Nodejs 进行网页抓取

Web Scraping with cheerio Nodejs

我试图在 MonsterIndia.com 上抓取零经验的工作,所以我使用 cheerio 和 nodejs 编写了以下代码,我观察到我可以通过搜索来搜索 php 工作喜欢 https://www.monsterindia.com/**php**-jobs.html 但如果我想搜索经验为零的 php 职位,我必须在网站上手动添加过滤器,但它不会反映在页面的 url 中,所以如何我能做到吗,我是网络抓取的初学者,请帮忙。

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);

您可以使用 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();
});

最好的方法是在 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;
  }
});