首页 > 解决方案 > 使用 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);

标签: javascriptnode.jsweb-scrapingcheerio

解决方案


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

推荐阅读